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

时间:2018-03-14 22:09:35

标签: vue.js axios interceptor

我试图让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);
            });

拦截器未被触发!

1 个答案:

答案 0 :(得分:6)

您在导入的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实例使用它,如图here in the 4. comment所示。

相关问题