小编典典

当多个API调用时,仅运行一次响应拦截器

reactjs

我有一个这样的拦截器

axios.interceptors.response.use(undefined, err=> {
    const error = err.response;
    console.log(error);
    if (error.status===401 && error.config && !error.config.__isRetryRequest) {
        return axios.post(Config.oauthUrl + '/token', 'grant_type=refresh_token&refresh_token='+refreshToken,
            { headers: {
          'Authorization': 'Basic ' + btoa(Config.clientId + ':' + Config.clientSecret),
          'Content-Type': 'application/x-www-form-urlencoded,charset=UTF-8'
         }
       })
        .then(response => {
          saveTokens(response.data)
          error.config.__isRetryRequest = true;
          return axios(error.config)
        })
      } 
  })

一切正常,但是如果我想在一个React
Component上调用4个API,并且发生此错误,则同一代码将运行4次,这意味着4次我将发送刷新令牌并获得auth令牌,并且我只想运行一次


阅读 475

收藏
2020-07-22

共1个答案

小编典典

我认为您可以使用以下方式将身份验证请求排队:

let authTokenRequest;

// This function makes a call to get the auth token
// or it returns the same promise as an in-progress call to get the auth token
function getAuthToken() {
  if (!authTokenRequest) {
    authTokenRequest = makeActualAuthenticationRequest();
    authTokenRequest.then(resetAuthTokenRequest, resetAuthTokenRequest);
  }

  return authTokenRequest;
}

function resetAuthTokenRequest() {
  authTokenRequest = null;
}

然后在您的拦截器中…

axios.interceptors.response.use(undefined, err => {
  const error = err.response;
  if (error.status===401 && error.config && !error.config.__isRetryRequest) {
    return getAuthToken().then(response => {
      saveTokens(response.data);
      error.config.__isRetryRequest = true;
      return axios(error.config);
   });
  } 
});

我希望这可以帮助你 ;)

2020-07-22