ajax - Axios 拦截器不会在页面加载时拦截

标签 ajax xmlhttprequest vue.js axios

我正在我的 Vue 应用程序中实现 JWT 以进行授权,并在使用 token 后刷新它们。

我使用了 axios 拦截器,因此我可以拦截对我的 API 后端的每个请求,这似乎适用于登录等......但是一旦我刷新页面,请求就会使用最后一个 token 正常发出。

问题是 axios 拦截器此时似乎不起作用,因此一旦使用了 token ,我就无法使用新的来更新它。

这是我设置拦截器的方式:-

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

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

最佳答案

试试这个

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

关于ajax - Axios 拦截器不会在页面加载时拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45648739/

相关文章:

javascript - Django如何制作一个首先运行js函数然后在.py中运行的按钮

javascript - 在 Chrome 应用中设置 XHR header 'Referer'

jquery - 禁用JQuery barrating rating star plugin hover and click effect

javascript - 使用 ajax POST/GET 调用请求露天身份验证 token (Angular)

javascript - vue.js 中的热图

javascript - NS_ERROR_FAILURE : Failure in Firefox

json - 打开网页,全选,复制到工作表

javascript - 用于寻找最佳实践的 jQuery 示例应用程序

laravel - 如何使用惯性 js 保留滚动按钮

vue.js - 将传递的 props 绑定(bind)到数据时,VueJs 不会更新