My development project involves the use of vuex, axios, vue-cookies, and JWTs. I have a specific file named api.js that is imported into the main Vue JS file. Below is the code snippet from api.js:
import axios from 'axios'
import Vue from 'vue'
import { store } from "@/store";
export default axios.create({
baseURL: store.state.endpoints.baseUrl,
headers: {
Authorization: `JWT ${Vue.$cookies.get('token')}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
Upon logging in through the login page, everything seems to be successful. The cookie 'token' value updates correctly with the new token in the browser inspector, Vuex indicates that the user is authenticated, and the router redirects me to the homepage. However, when attempting to navigate to a page on the homepage that requires authentication, the header passes 'JWT null' instead of the actual token from the cookie, leading to a failure and trapping me in a loop of successful login but inability to proceed.
If I log in and then refresh the page before doing anything else, everything functions as expected and the JWT is no longer null. It seems like the issue lies in the api.js code mentioned earlier not properly retrieving the token from the cookie each time it is called, but only upon page refresh. Could this be due to caching or do I need to somehow reload this import after logging in?
For additional context, here's a snippet of code from my login page showcasing how the data is updated post-login:
api.post(this.$store.state.endpoints.obtainJWT, payload)
.then((response) => {
console.log("Token - "+response.data.token);
console.log("Profile - "+response.data.user);
this.$cookies.set('token', response.data.token);
this.$store.commit("setAuthUser",
{authUser: response.data, isAuthenticated: true})
})
.then(() => this.$router.push({path: '/'}))
.catch((error) => {
console.log("Error!");
console.log(error);
console.debug(error);
console.dir(error);
})
Here's an example of an API call that displays 'JWT null' if accessed before refreshing the page:
import api from "../api.js";
...
api.get("/data_full/" + id)
.then((response) => {
this.title = response.data.title;
})
Lastly, in my project's main.js file, I have the import for api.js:
...
import api from './api.js'
...
Vue.$http = api;