關於Axios的封裝中獲取localstorage緩存的token不更新的問題


來自 https://www.h5w3.com/144598.html 侵刪

vue項目中使用axios作為ajax請求插件,由於異步的原因,項目初始化之后axios獲取的localstorage中緩存的token,在無刷新的情況下,localstorage緩存的token並不會被axios檢測到更新,解決方案如下:
1、在獲取到token的時候就設置axios header中的認證信息

 

 

  // 設置token信息並緩存

 

setToken (state, data) {

state.token = data

store.set('token', data)

// 設置axios header認證信息

axios.defaults.headers.token = data

}

 

 

2、在axios封裝中獲取localstorage緩存的token

 

 

// 設置認證信息

 

axios.defaults.headers.token = store.get('token')

 

//-----------------------------------

//token刷新實時獲取新token
axios.defaults.headers['author-token-key'] = localStorage.getItem('token')

 

//------------或者調用的時候 

async _getToken() {
      await getToken(this.parmasList).then((res) => {
        if (res.data.code == 200) {
          //存儲token 替換原有token,原來token備份
          localStorage.setItem("tokenBack", localStorage.getItem("token"));
          localStorage.setItem("token", res.data.data);
        }
      });
    },

 

//-----------------------

方法放到里面

getToken(this.parmasList)
        .then((res) => {
          if (res.data.code == 200) {
            //存儲token 替換原有token,原來token備份
            localStorage.setItem("tokenBack", localStorage.getItem("token"));
            localStorage.setItem("token", res.data.data);
            this.$router.push({
              path: "/home",
              query: {
                type: type,
              },
            });
          }
        })
        .finally(() => {
          this.$router.push({
            path: "/home",
            query: {
              type: type,
            },
          });
        });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM