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

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

拦截器没有触发!

最佳答案

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

调用 window.axios = axios.create() 无论如何都是非常糟糕的风格,你应该不惜一切代价避免它。如果你想让它全局可用,你应该将它绑定(bind)到 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 .

关于vue.js - Axios 请求拦截器在我的 vue 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288415/

相关文章:

vue.js - 在 Quasar (vuejs) 的其他引导文件中使用来自引导文件的依赖项

android - 无法在 axios 上发出 POST 请求(React-Native)

java - Mybatis拦截器执行顺序

node.js - 204 错误代码然后 500 错误代码响应

java - 拦截器的@AroundInvoke未触发

java - 如何在 EJBClientInterceptor 中管理状态

javascript - 尝试将查询绑定(bind)到 Vue.js 中 api 的每个请求的 json 字符串

javascript - 将更改从子级发送给父级

javascript - 如何在 vue.js 2 上使用 Laravel 的 baseurl?

reactjs - componentDidMount 生命周期方法中子组件抛出的错误未在错误边界中捕获