加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax – Axios拦截器不拦截页面加载

发布时间:2020-12-16 02:46:52 所属栏目:百科 来源:网络整理
导读:我正在将JWT实现到我的Vue应用程序中以进行授权,并在使用它后刷新我的令牌. 我已经使用了axios拦截器,因此我可以拦截每个请求到我的API后端,这似乎适用于登录等…但是一旦我刷新页面,请求就像使用最后一个令牌一样正常. 问题是axios拦截器此时似乎不起作用,
我正在将JWT实现到我的Vue应用程序中以进行授权,并在使用它后刷新我的令牌.

我已经使用了axios拦截器,因此我可以拦截每个请求到我的API后端,这似乎适用于登录等…但是一旦我刷新页面,请求就像使用最后一个令牌一样正常.

问题是axios拦截器此时似乎不起作用,所以一旦使用了令牌,我就无法使用新的令牌来更新它.

以下是我设置拦截器的方法: –

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.

我在root应用程序的beforeMount方法中设置拦截器.我已经尝试过将它们移到创建之前,我仍然遇到同样的问题.

解决方法

试试这个

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读