VueJS set axios header persist

2019-08-16 07:57发布

问题:

I've had a problem which my vuex state's only lasts for web page refresh. Once web page is refreshed, data in the vuex store is vanished.

For overcome that I've used nice pluggin called Vuex persistestate Now my vuex is persist.

But still I've a issue with the axios authorization header. I've set auth header in axios login action like this

actions: {
    login({ commit }, payload) {
      return new Promise((resolve, reject) => {
        try {
          axios.defaults.headers.common.Authorization = payload.token;
          commit('setUser', payload);
          resolve();
        } catch (error) {
          reject();
        }
      });
    },
  },

But this auth headers value got undefined if I hit the refresh button. How do I overcome this problem?

回答1:

It's because in the last session you called login and it saves the token in your axios instance. On refresh, the headers setting is gone. Vuex persisted state only save your Vuex, and your token is not in your Vuex.

I use js-cookie here.

// login action
   ...
   axios.defaults.headers.common.Authorization = payload.token;
   Cookies.set('token, payload.token);
   commit('setUser', payload);
   resolve();
   ...
// Put it somewhere in the entry of your application, e.g: `main.js`, `App.vue`.
axios.defaults.headers.common.Authorization = Cookies.get(token);