解決token過期問題


login時獲取了兩個token,一個token,一個refresh_token,當token過期時,通過refresh_token再請求新的token,存到本地存儲中。

// 響應攔截器
request.interceptors.response.use(
  // 響應成功進入第1個函數
  // 該函數的參數是響應對象
  function(response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  // 響應失敗進入第2個函數,該函數的參數是錯誤對象
  async function(error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    // 如果響應碼是 401 ,則請求獲取新的 token

    // 響應攔截器中的 error 就是那個響應的錯誤對象
    console.dir(error);
    if (error.response && error.response.status === 401) {
      // 校驗是否有 refresh_token
      const user = store.state.user;

      if (!user || !user.refresh_token) {
        router.push("/login");

        // 代碼不要往后執行了
        return;
      }

      // 如果有refresh_token,則請求獲取新的 token
      try {
        const res = await axios({
          method: "PUT",
          url: "http://ttapi.research.itcast.cn/app/v1_0/authorizations",
          headers: {
            Authorization: `Bearer ${user.refresh_token}`
          }
        });

        // 如果獲取成功,則把新的 token 更新到容器中
        console.log("刷新 token  成功", res);
        store.commit("setUser", {
          token: res.data.data.token, // 最新獲取的可用 token
          refresh_token: user.refresh_token // 還是原來的 refresh_token
        });

        // 把之前失敗的用戶請求繼續發出去
        // config 是一個對象,其中包含本次失敗請求相關的那些配置信息,例如 url、method 都有
        // return 把 request 的請求結果繼續返回給發請求的具體位置
        return request(error.config);
      } catch (err) {
        // 如果獲取失敗,直接跳轉 登錄頁
        console.log("請求刷線 token 失敗", err);
        router.push("/login");
      }
    }


免責聲明!

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



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