Search code examples
javascriptvue.jsaxiosnativescriptvuex

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?


Solution

  • I don't know if it can be helpful, but I use to initialize a custom Axios instance.

    scripts/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();
    

    No store.js code because I simply import nativescript-vue, vuex and (if needed) axiosConfig object.

    I've never had circular problems this way, hope it helps