Categories
axios javascript vue.js

bearer token undefined with global axios config

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?