Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy...
I've gone through various tutorials and read numerous posts on stackoverflow, but everything still seems unclear to me.
When I add a debugger, it works fine, but as soon as I switch to "axios.interceptors" it gives me an error saying axios is undefined, which is puzzling...
import axios from 'axios';
debugger;
axios.interceptors.response.use(function (response) {
console.log(response);
// Any status code that falls within the range of 2xx causes this function to trigger
// Do something with response data
return response;
}, function (error) {
console.log(error);
// Any status codes outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
const token = localStorage.getItem('token');
export default axios.create({
baseURL: process.env.VUE_APP_URL_API,
headers: {
Authorization: `Bearer ${token}`
}
})
The above code is used in my VueX Store.
import Http from "../../api/http";
export default {
state: {
customers: {},
customer: {},
},
getters: {
customers: state => state.customers,
},
mutations: {
SET_CUSTOMERS(state, customers) {
state.customers = customers;
}
},
actions: {
loadCustomers({commit}) {
Http.get('/customers').then(result => {
commit('SET_CUSTOMERS', result.data.data );
}).catch(error => {
throw new Error(`API ${error}`);
});
}
}
};
I am trying to detect HTTP status code 401 to log out the user and delete the token from the browser.
If anyone has any insights or solutions, I would greatly appreciate your help. Thank you so much.
Best regards, Christophe