簡體   English   中英

Axios Eject:如何進行?

[英]Axios Eject: How to proceed?

當按以下方式設置攔截器時,我是否可以退出它們? 這是一個React應用程序,我在index.js中有以下代碼用於所有全局axios調用。

在我的onRefreshToken()調用中,我想以某種方式彈出全局響應攔截器,以向刷新令牌API發送新請求。 我已經看到了一些使用變量或函數調用的人的示例,但是不確定如何實現。

請求攔截器

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token');
    config.headers.authorization = `Bearer ${token}`;
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

響應攔截器

axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    const errorMessage = error.message;
    const substring = '401';
    const errorCheck = errorMessage.includes(substring);

    return new Promise((resolve, reject) => {
      if (errorCheck) {
        onRefreshToken({
          initialRequest: error.config,
          resolve,
          reject,
        });
      } else {
        refreshFailLogout();
        reject(error);
      }
    });
  },
);

我能夠使我處理此要求的實例正常工作。 盡管可以改進,但是我遵循Shinework的方法對API access_token和refresh_token TTL進行了一些調整。 如果有人想知道如何更詳細地處理此問題,請告訴我,我可以添加更多方法,可以在不彈出請求和響應攔截器的情況下使它起作用。 注意:這是在React,Redux(帶有Thunk)和React-Router應用程序中。

我知道那里沒有很多文檔,因此,如果您遇到麻煩,請尋求幫助! 使它正常工作的關鍵功能:

axios.interceptors.response.use(
  (response) => {
    // eslint-disable-next-line no-console
    console.log('Response Success', response);
    // Do something with response data
    return response;
  },
  (error) => {
    // eslint-disable-next-line no-console
    console.log(error.response);
    return new Promise((resolve, reject) => {
      if (
        error.response.status === 401
        && error.config.headers.Authorization === 'Bearer undefined'
      ) {
        refreshFailLogout();
        reject(error);
      } else if (error.response.status === 401) {
        onRefreshToken({
          initialRequest: error.config,
          resolve,
          reject,
        });
      } else {
        refreshFailLogout();
        reject(error);
      }
    });
  },
);

放置您的redux調度,在saveTokens和refreshFailLogout中進行操作調用。 這適用於較小的TTL的用例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM