Axios interceptor doesn't intercept on page load

爱⌒轻易说出口 提交于 2019-12-23 10:28:10

问题


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.


回答1:


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); });


来源:https://stackoverflow.com/questions/45648739/axios-interceptor-doesnt-intercept-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!