您能帮我解决这个问题吗?
我需要在出错时刷新令牌并重试失败的请求。
我有:
axios.interceptors.response.use(function(response) {
return response;
}, function(error) {
const originalRequest = error.config;
if(error.response.status===401 && !originalRequest._retry) {
originalRequest._retry = true;
setTimeout(async function() {
const refreshedHeader = await setHeader()
console.log('New header: ', refreshedHeader)
axios.defaults.headers = refreshedHeader
originalRequest.headers = refreshedHeader
console.log('Original Request: ', originalRequest)
return axios(originalRequest)
}, 2000);
}
return Promise.reject(error);
});
setHeader()是这样的:
const setHeader = async () => {
const token = await refreshToken()
const header = {
Authorization: `Bearer ${token}`,
};
return header
}
是否提取了新令牌并更新了标头,但重试失败,仍然显示401?
答案 0 :(得分:1)
这是因为超时。这个:
return Promise.reject(error);
将始终在超时完成之前返回错误。 尝试删除该超时并将错误功能设置为异步。
axios.interceptors.response.use(function(response) {
return response;
}, async function(error) {
const originalRequest = error.config;
if (error.response.status===401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshedHeader = await setHeader()
console.log('New header: ', refreshedHeader)
axios.defaults.headers = refreshedHeader
originalRequest.headers = refreshedHeader
console.log('Original Request: ', originalRequest)
return axios(originalRequest);
}
return Promise.reject(error);
});
否则,请尝试以下操作:
axios.interceptors.response.use(function(response) {
return response;
}, async function(error) {
await new Promise(function(res) {
setTimeout(function() {res()}, 2000);
});
const originalRequest = error.config;
if (error.response.status===401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshedHeader = await setHeader()
console.log('New header: ', refreshedHeader)
axios.defaults.headers = refreshedHeader
originalRequest.headers = refreshedHeader
console.log('Original Request: ', originalRequest)
return axios(originalRequest);
}
return Promise.reject(error);
});
这将阻止其余所有内容2秒钟,然后解决或拒绝它。