Axios请求拦截器无法正常工作

Jen*_*sen 6 interceptor vue.js axios

我正在尝试让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)
})
Run Code Online (Sandbox Code Playgroud)

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

axios.get('users').then((data) => {
                console.log(data);
            });
Run Code Online (Sandbox Code Playgroud)

拦截器没有被触发!

Phi*_*ann 11

您在导入的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
Run Code Online (Sandbox Code Playgroud)

如果你真的希望它在任何地方都可以使用而不必导入它,可以考虑将我的代码从上面包装到Vue插件中,然后让你的Vue实例使用它,如4.注释中所示.

  • 如果我想捕获所有axios请求,如何配置拦截器? (2认同)