Global http response error handling in vue/axios with vuex

前端 未结 3 1366
难免孤独
难免孤独 2021-01-22 19:59

I\'m trying to fix a behavior in my VueJS SPA wherein a limbo state arises. The app doesn\'t know the JWT has already expired and therefore presents itself as if the user is sti

相关标签:
3条回答
  • 2021-01-22 20:31

    What about direct import your store to ApiClient.js? Something like

    const axios = require('axios')
    import store from 'path/to/store'
    
    const errorHandler = (error) => {
    if (error.response.status === 401) {
      store.dispatch('user/logout') // now store should be accessible
    }
      return Promise.reject({ ...error })
    }
    
    
    export default class API {
      constructor(options) {
        this.options = Object.assign({ basePath: '' }, options)
        this.axios = axios.create({ timeout: 60000 })
        this.axios.interceptors.response.use(
          response => response,
          error => errorHandler(error)
        )
      }
      // ...
    }
    
    0 讨论(0)
  • 2021-01-22 20:33

    Base on these thread I was able to manage a solution for my needs:

    main.js

    import api, {apiConfig} from 'Api/api'
    apiConfig({ store: $store });
    

    ApiClient.js

    let configs = {
      store: undefined,
    };
    const apiConfig = ({ store }) => {
      configs = { ...configs, store };
    };
    export default api;
    export { apiConfig };
    

    This way the api.js file will require a configuration that can later be expanded.

    0 讨论(0)
  • 2021-01-22 20:56

    main.js:

    import store from './store';
    
    const Instance = new Vue({
      store,
      ...
    })
    
    export const { $store } = Instance;
    

    Now you can import { $store } from '@/main.js' anywhere you want. And it's going to be the same instance you have mounted in your app, not a new Vuex.Store({}) (which is what ./store exports, each time you import it somewhere else).

    You can export the same way anything else you might want to use in services, tests, helpers, etc... I.e:

    export const { $store, $http, $bus, $t } = Instance;
    
    0 讨论(0)
提交回复
热议问题