8

我有一个这样的拦截器

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 组件进行 4 次 API 调用,并且发生此错误,则相同的代码将运行 4 次,这意味着我将发送 4 次刷新令牌并获取身份验证令牌,并且我显然只想运行一次

4

2 回答 2

13

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

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

我希望这可以帮助你 ;)

于 2016-09-16T08:41:09.200 回答
2

您是否考虑过请求的节流/去抖动包装器?lodash 都内置了。这是两者的一个很好的例子。尽管有下划线但相同的区别。

http://jsfiddle.net/missinglink/19e2r2we/

...对于您的情况可能是这样的吗?

axios.interceptors.response.use(undefined, err=> {
    const error = err.response;
    console.log(error);
    if (error.status===401 && error.config && !error.config.__isRetryRequest) {
        return _.debounce(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)
        }), 1000)
      } 
  })

像这样可能会更好吗? axios.interceptors.response.use(undefined, _.debounce(

于 2016-09-15T12:31:19.290 回答