将vuex存储导入axios和app.js文件

使用NativeScript vue。我将axios放在了自己的文件中,可以在其中添加拦截器等(在这种情况下,可以处理JWT刷新令牌)。在我的vuex存储(ccStore)中,我已经存储了authToken和refreshToken。我正在使用vuex坚持。

    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;

在我的app.js文件中,导入此修改后的axios,并将其分配给

Vue.prototype.$http = axios;

我这样做是为了在每个组件中都可以使用带有拦截器的axios的相同实例[昨晚在重构时遇到了一些问题-当将修改后的axios包含在每个组件的已挂接的钩子中时是循环引用...但是将其全局粘贴似乎有效]

但是,在我的app.js文件中,我还调用ccStore,以便可以将其附加到vue实例上。我这样做对吗?app.js和axios是否都引用了ccStore的同一实例?

另外-为了进一步改变思路,我在vuex商店中有一些需要axios的操作...因此,我也不得不在我的vuex商店文件中包含axios-但是axios已经包括了我的vues商店...

所以...

app.js导入store和axios,store导入axios,axios导入store

这也不是圆形的吗?

汤姆

我不知道它是否有帮助,但是我使用它来初始化自定义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);
    }
}

app.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对象(如果需要)。

我从来没有这样的循环问题,希望对你有帮助

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章