VueJS set axios header persist

心不动则不痛 提交于 2019-12-13 03:47:15

问题


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);


来源:https://stackoverflow.com/questions/56625567/vuejs-set-axios-header-persist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!