Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios interceptor doesn't intercept on page load

I am implementing JWT into my Vue application for authorization and I refresh my tokens once they are used.

I have used axios interceptors so I can intercept every request to my API backend and this seems to work on login etc... but once I refresh the page the request is made as normal using the last token.

The problem is the axios interceptors don't seem to work at this point, so once the token has been used I can't update it with the new one.

Here's how I'm setting my interceptors:-

window.axios.interceptors.request.use(function (config) {
    console.log("Sent request!");

    return config;
}, function (error) {
    console.log("Failed sending request!");

    return Promise.reject(error);
});

window.axios.interceptors.response.use(function (response) {
    console.log("Got headers:", response.headers);
    if (response.headers.hasOwnProperty('authorization')) {
        console.log("Got authorization:", response.headers.authorization);
        Store.auth.setToken(response.headers.authorization);
    }

    return response;
}, function(err){
    console.log("Got error", err);
});

I don't get any of the console.log's on page load.

I am setting my interceptors in the root app's beforeMount method. I've tried moving them to beforeCreate and I still get the same issue.

like image 694
Polarize Avatar asked Nov 07 '22 18:11

Polarize


1 Answers

try this

window.axios.interceptors.request.use(function (config) {
console.log("Sent request!");

if(localStorage.getItem('id_token')!=undefined){
    config.headers['Authorization'] = 'Bearer '+localStorage.getItem('id_token')
}
return config;}  , function (error) {
console.log("Failed sending request!");

return Promise.reject(error); });
like image 173
kishore.k.vaishnav Avatar answered Nov 14 '22 21:11

kishore.k.vaishnav