我正试图让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所示.

Vue.js相关问答推荐

在VueJS中卸载元素之前是否应该删除JavaScript事件收件箱?

将Vite Vuejs应用部署到Apache服务器

保持页面重新加载之间的状态

如何使用 vue.js 和 vue 路由实现当前路由的子菜单的子菜单

Vuejs 和 Laravel 发布请求 CORS

Vue 单元测试:您正在开发模式下运行 Vue?

Vue:限制文本区域输入中的字符,截断过滤器?

在 SASS 中使用 Vuetify 类

如何像 React 中的 {...props} 一样在 Vue 中解构 props?

Vuejs 2,VUEX,编辑数据时的数据绑定

Axios-一次发出多个请求(vue.js)

Vue路由安全

如果我刷新我的网页,Vuex store是空的

如何在 NuxtJS 中设置全局 $axios 标头

如何从方法内部访问数据

如何在 vue.js 2 上循环对象观察者?

是否有 v-cloak 逆?

Vue js在列表中添加动态字段,删除和排序不起作用

Vuetify 离线文档

使用 vue.js 获取调用元素