Axios拦截器不会在页面加载时拦截 [英] Axios interceptor doesn't intercept on page load

查看:286
本文介绍了Axios拦截器不会在页面加载时拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将JWT实施到我的Vue应用程序中以进行授权,并且一旦使用了令牌,便会刷新它们.

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

我使用了axios拦截器,因此我可以拦截对API后端的每个请求,这似乎可以在登录等方面工作……但是,一旦刷新页面,该请求便会使用上一个令牌正常进行.

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.

问题在于axios拦截器目前似乎无法正常工作,因此一旦使用了令牌,就无法使用新令牌进行更新.

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

在页面加载中我没有得到任何console.log.

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

我在根应用程序的beforeMount方法中设置拦截器.我尝试将它们移动到beforeCreate,但仍然遇到相同的问题.

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.

推荐答案

尝试一下

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

这篇关于Axios拦截器不会在页面加载时拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆