首页 > 解决方案 > import vuex store into axios and app.js file

问题描述

Using NativeScript vue. I have put axios in its own file, where I can add interceptors etc (in this case to handle a JWT refresh token). In my vuex store (ccStore) I have stored the authToken, and refreshToken. I'm using vuex persist.

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


    const DEV_BASE_URL = ccStore.getters.getBaseURL  // local ip injected by webpack
    const PROD_BASE_URL = ''    

    axios.defaults.baseURL = (TNS_ENV === 'production') ? PROD_BASE_URL : DEV_BASE_URL


    axios.interceptors.request.use( function (config) {
            let token = ''
            if(config.url.includes('/auth/refresh')) { //use the refresh token for refresh endpoint
                token = ccStore.getters.getRefreshToken;
            } else { //otherwise use the access token
                token = ccStore.getters.getAuthToken;
            }
            if (token) {
                config.headers['Authorization'] = `Bearer ${token}`
            }
            return config
        },
        function (error) {
            console.log(error)
            return Promise.reject(error)
        }
    )

    axios.interceptors.response.use(
        function(response) {
            console.log(response)
            return response
        },
        function(error) {
            const originalRequest = error.config
            if(error.response && error.response.status === 401) {
                if (originalRequest.url.includes('/auth/refresh')) { //the original request was to refresh so we must log out
                    return ccStore.dispatch('logout')
                } else {
                    return ccStore.dispatch('refreshToken').then(response => { //try refreshing before logging out
                        return axios(originalRequest)
                    })
                }
            } else {
                console.log(error)
                return Promise.reject(error)
            }
        }
    )

    export default axios;

In my app.js file, I import this modified axios, and assign it to

Vue.prototype.$http = axios;

I did this so that the same instance of axios with interceptors is available in every component [ I ran into some problems doing a refactor last night - circular references when including my modified axios in the mounted hook of each component... but sticking it globally seems to work ]

However, in my app.js file I am also calling ccStore so that I can attach it to my vue instance... Am I doing this right? Is the same instance of ccStore being referenced in both app.js and axios?

Also - to bend the mind further, I have some actions within my vuex store for which I need axios... so I am also having to include axios within my vuex store file - yet axios already includes my vues store...

so...

app.js imports store and axios, store imports axios, axios imports store

Is this not circular too?

标签: javascriptvue.jsaxiosnativescriptvuex

解决方案


我不知道它是否有帮助,但我用来初始化一个自定义的 Axios 实例。

脚本/axios-config.js

import axios from 'axios';
import store from '../store';
import Vue from 'nativescript-vue';

export default {
    endpoint: "https://myendpoint.com",

    requestInterceptor: config => {
        config.headers.Authorization = store.getters.getToken;
        return config;
    },

    init() {
        Vue.prototype.$http = axios.create({ baseURL: this.endpoint });
        Vue.prototype.$http.interceptors.request.use(this.requestInterceptor);
    }
}

应用程序.js

import Vue from 'nativescript-vue';
import store from './store';
import axiosConfig from './scripts/axios-config';
import router from './router'; // custom router

axiosConfig.init();

// code

new Vue({
    render: h => h('frame', [h(router['login'])]),
    store
}).$start();

没有 store.js 代码,因为我只是导入 nativescript-vue、vuex 和(如果需要)axiosConfig 对象。

我从来没有以这种方式遇到过循环问题,希望对您有所帮助


推荐阅读