I need to access an Express REST API that demands a valid json web token for certain routes. In order to include the token from localstorage every time I needed, I had to create an "Axios config file".
My http.js file includes the code below:
import Vue from "vue";
import axios from "axios";
const devInstance = createInstance("http://localhost:3000");
devInstance.interceptors.request.use(config => {
console.log(config);
return config;
}, err => {
console.log(err);
return Promise.reject(err);
});
devInstance.interceptors.response.use(res => {
console.log(res);
return res;
}, err => {
console.log(err);
return Promise.reject(err);
});
const productionInstance = createInstance("http://www.myApi.com");
function createInstance(baseURL){
return axios.create({
baseURL,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.token}`
}
});
}
Vue.prototype.$http = devInstance; // Check debug/build mode
In my main.js, I import this instance once:
import http from "./http.js";
and now I can use this.$http
to access the global axios instance without having to import it again.
However, when trying to consume the API, localStorage.token
returns undefined because it is not set during instance creation.
Is there a way to automatically update the Authorization
attribute without manually passing the token each time?