开发者问题收集

Axios 请求拦截器在我的 Vue 应用程序中不起作用

2018-03-14
29086

我试图让 axios 与请求拦截器一起工作。但是 在发出请求之前,拦截器没有被触发。这里可能出了什么问题?我已经对这个问题进行了大量研究,但到目前为止还没有找到解决方案。可以在这里寻求一些帮助!这是我的代码:

import VueRouter from 'vue-router';
    import Login from './components/Login.vue'
    import Home from './components/Home.vue'
    import axios from 'axios';

    window.Vue = require('vue');
    
    window.axios = axios.create({
        baseURL: 'http://localhost:8080',
        timeout: 10000,
        params: {} // do not remove this, its added to add params later in the config
    });
    
    
    Vue.use(VueRouter);
    
    // Check the user's auth status when the app starts
    // auth.checkAuth()
    
    
    const routes = [
        { path: '/', component: Login, name: 'login' },
        { path: '/home', component: Home, name: 'home', beforeEnter: requireAuth },
    ];
    
    const router = new VueRouter({
        routes // short for `routes: routes`
    });
    
    const app = new Vue({
        router
    }).$mount('#app');
    
    function requireAuth (to, from, next) {
        if (!loggedIn()) {
            router.push('/');
        } else {
            next()
        }
    }
    
    function loggedIn() {
        return localStorage.token !== undefined;
    }
    
    
    axios.interceptors.request.use(function (config) {
       alert('test');
    
        return config;
    }, function (error) {
        // Do something with request error
        return Promise.reject(error)
    })

当我在另一个 vue 文件中使用 axios 时:

axios.get('users').then((data) => {
                    console.log(data);
                });

拦截器未触发!

2个回答

您正在调用您导入的 axios 实例上的拦截器,但它需要在您创建的实例上。

无论如何,调用 window.axios = axios.create() 都是非常糟糕的风格,您应该不惜一切代价避免它。如果您希望它在全球范围内可用,您应该将其绑定到 Vue Prototype。更好的方法是将其移出另一个模块:

const instance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000,
    params: {} // do not remove this, its added to add params later in the config
});

instance.interceptors.request.use(function (config) {
   alert('test');

    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error)
})

export default instance

如果您真的希望它在任何地方都可用而不必导入它,请考虑将上面的代码包装在 Vue 插件中并让您的 Vue 实例使用它,如 此处第 4. 条注释 所示。

Philip Feldmann
2018-03-14
axios.interceptors.response.use(async function (response) {
    return response;
}, async function (error) {
    if (error.response.status === 401) {
        //call your api for refresh token
        error.config.headers[
            "Authorization"
        ] = `bearer ${token from your result}`;
        return axios(error.config);
    }
    return Promise.reject(error);
});

通过使用以上代码您可以自动调用当前的 api url。

Pallavi
2022-02-25