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

Axios request interceptor is not working in my vue app

我正在尝试让 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);
                });

拦截器没有触发!

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

调用 window.axios = axios.create() 无论如何都是非常糟糕的风格,你应该不惜一切代价避免它。如果你想让它全局可用,你应该将它绑定到 Vue 原型。更好的办法是将它移出另一个模块:

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 实例使用它,如图 here in the 4. comment.

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

使用上面的代码可以自动调用当前的apiurl.