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

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

问题描述:

我正在尝试使axios与请求拦截器一起使用.然而 在发出请求之前,不会触发拦截器.这里可能出什么问题了?关于这个问题,我已经很多了,但没有 到目前为止找到了解决方案.可以在这里使用一些帮助!这是我的代码:

I'm trying to make axios working with a request interceptor. However before a request is made the interceptor is not triggered. What could be going wrong here? I've red already a lot about this problem but not found a solution so far. Could use some help here! This is my code:

    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时:

When I use axios within another vue file:

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

拦截器未触发!

您是在导入的axios实例上调用拦截器,但它必须在您创建的实例上.

You're calling the interceptor on the axios instance you imported, but it needs to be on the instances you created.

无论如何,调用window.axios = axios.create()确实是不好的风格,您应该不惜一切代价避免使用它.如果您希望它在全球范围内可用,则应将其绑定到Vue原型.更好的办法是将其移出另一个模块:

Calling window.axios = axios.create() is really bad style anyway and you should avoid it at all costs. If you want it to be globally available you should bind it to the Vue Prototype. Even better would be to move it out in another module:

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实例使用它,如下所示:

If you really want it to be available everywhere without having to import it, consider wrapping my code from above inside a Vue plugin and let your Vue instance use it, as shown here in the 4. comment.