当多个API调用时,只运行一次响应拦截器
run response interceptor only once when multiple API calls
我有一个像这样的拦截器
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)
})
}
})
和一切都在工作,但如果我喜欢在我的情况下4个API调用一个React组件,这个错误发生相同的代码将运行4次,这意味着4次我将发送我的刷新令牌,并获得认证令牌,我想只运行一次显然
我认为您可以使用以下方式对身份验证请求进行排队:
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);
});
}
});
您考虑过为请求使用节流/脱包器吗?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(
相关文章:
- Javascript返回值只在循环中返回一次
- Jquery FadeIn FadeOut 只工作一次
- Javascript html每点击一次就会更改url
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- Rails操作只调用一次,但我在ajax中每秒钟都调用一次
- jQuery滚动功能只工作一次
- 刷新导致我的帖子“;张贴“;再一次
- 在上一次响应时隐藏Qualtrics项目-Javascript
- 运行 ajax 函数以每 3 秒检查一次 json 响应
- 如何使用 Ajax 一次仅按顺序发布数组的 1 个值,并在继续之前等待响应
- 每 XX 秒调用一次 GET API,并将 JSON 响应放入 CSV 中
- mobilesafari 5在下一次行动之前没有响应js事件
- 需要xml数据来保持每2秒POST一次,直到收到响应
- Ajax响应只工作一次-使用PHP的购物车
- AJAX请求的响应只显示一次
- jQuery中的调用函数ajax成功响应工作一次,而不是两次
- 当多个API调用时,只运行一次响应拦截器
- 烬:每5秒轮询一次api,但要在获得前一次调用的响应之后
- setInterval响应仅一次,而不是1000
- iPad上的响应式设计只适用于一次