Reputation:
I created a Vue app using Axios. I installed Axios via Vue UI dependency installation. In my main.js file I added a global configuration
import Vue from "vue";
import "./plugins/vuetify";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import axios from "axios";
Vue.config.productionTip = false;
axios.defaults.baseURL = "http://localhost:3000";
axios.defaults.headers.common["Authorization"] = `Bearer ${localStorage.token}`;
axios.defaults.headers.post["Content-Type"] = "application/json";
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
When I want to signOut
I execute this
signOut: async function() {
try {
const response = await axios.post("/users/signout");
// go on
} catch (err) {
// err handling
}
}
but the post headers return an undefined token Bearer undefined
. So I removed this line
axios.defaults.headers.common["Authorization"] = `Bearer ${localStorage.token}`;
from the main.js file and used this code
signOut: async function() {
try {
const request = axios.create({
baseURL: "http://localhost:3000/users/signout"
});
request.defaults.headers.common['Authorization'] = `Bearer ${localStorage.token}`;
const response = await request.post();
// go on
} catch (err) {
// err handling
}
}
and this works fine. The Authorization
header got setup correctly. Why does it work now? How can I fix the first approach?
Upvotes: 3
Views: 3528
Reputation: 298
Since you are setting the authorization header in your main.js
it will be executed once when the app start. If in your localStorage
that token is not present it will be undefined
and will stay that way until a request has it's own token. Now in the second approach you have your token present in your localStorage
, and so it will correctly set the header.
In your first approach you can fix this by removing that Authorization
header assignment and assigning the token in your requests directly or create a function that will assign the default header auth whenever the token from the server changes (or is removed).
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
const auth = token ? `Bearer ${token}` : '';
config.headers.common['Authorization'] = auth;
return config;
},
error => Promise.reject(error),
);
This way before each request our token will be re-read from localStorage and the updated Bearer token will be set in the header.
Upvotes: 5