使用vuex在vue 2 JS中的Axios拦截器

vue.js Vue.js

GO蛋蛋

2020-03-12

我将成功登录调用后的令牌存储在vuex存储中,如下所示:

axios.post('/api/auth/doLogin.php', params, axiosConfig)
    .then(res => {
        console.log(res.data); // token
        this.$store.commit('login', res.data);
    })

axiosConfig是我仅设置baseURL的文件,export default { baseURL: 'http://localhost/obiezaca/v2' }而params只是发送到后端的数据。

我的vuex文件看起来是:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        logged: false,
        token: ''
    },
    mutations: {
        login: (state, response) => {
            state.logged = true;
            state.token = response;
            console.log('state updated');
            console.log('state.logged flag is: '+state.logged);
            console.log('state.token: '+state.token);
        },
        logout: (state) => {
            state.logged = false;
            state.token = '';
        }
    }
});

它工作正常,我可以基于v-if="this.$store.state.logged"已登录的用户重新呈现SPA中的某些内容我可以this.$store.state.logged从整个应用程序中的任何组件进行访问

现在,我想将令牌添加到每个调用我的其余API后端的请求中。我创建了基本的axios http拦截器,如下所示:

import axios from 'axios';

axios.interceptors.request.use(function(config) {
    const token = this.$store.state.token;
    if(token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
}, function(err) {
    return Promise.reject(err);
});

现在我对此有2个问题。

  1. 我知道,它是提供给使用this.$store.state.loggedthis.$store.state.token跨越每一个部件,但我可以用它在单一的JavaScript文件一样吗?
  2. Where should I execute/start my interceptor javascript file? It is independent file which lays in my app main folder but I am not calling it anywhere, in angularJS which I was working before, I had to add $httpProvider.interceptors.push('authInterceptorService'); in config but I don't know how to do same thing in vue architecture. So where should I inject my interceptor?

EDIT

I followed GMaiolo tips I added

import interceptor from './helpers/httpInterceptor.js';
interceptor();

to my main.js file and I refactor my interceptor to this:

import axios from 'axios';
import store from '../store/store';

export default function execute() {
    axios.interceptors.request.use(function(config) {
        const token = this.$store.state.token;
        if(token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    }, function(err) {
        return Promise.reject(err);
    });
}

Result of this changes is that every already existing backend calls ( GET ) which don't need token to work stopped working but it is logical because I didn't clarified to which request it should add token so it is trying to add it everywhere and in my interceptor something is still wrong and that is why every already exisitng request stopped working.

当我尝试在浏览器控制台中进行后端POST调用时,仍然出现此错误:

TypeError:无法读取未定义的属性“ $ store”

虽然我将存储导入到我的拦截器文件中。有任何想法吗?如果需要,我可以提供更多信息。

我还添加了此主要,存储和拦截器树结构的屏幕截图,因此您可以看到我正在导入fron正确的路径:

路径

第1365篇《使用vuex在vue 2 JS中的Axios拦截器》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android