【问题标题】:import vuex store into axios and app.js file将 vuex 存储导入 axios 和 app.js 文件
【发布时间】:2019-10-16 22:41:08
【问题描述】:

使用 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, 存储导入 axios, axios 导入商店

这不是圆形的吗?

【问题讨论】:

    标签: javascript vue.js axios nativescript vuex


    【解决方案1】:

    我不知道它是否有帮助,但我用来初始化一个自定义的 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 对象。

    我从来没有遇到过这种循环问题,希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-12-07
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 2022-11-16
      • 2018-01-20
      • 2022-09-23
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多