我正在尝试在Axios请求拦截器中发送请求。在发送任何其他请求之前,我需要等待该请求完成。 (用例正在刷新access_token)
问题是请求从未发送过,并抛出undefined
异常。
这是我在做什么:
注册拦截器:
api.interceptors.request.use(handleInterceptRequest);
使用该拦截器在每个请求之前检查过期的令牌:
async function handleInterceptRequest(config) {
if(config.url === '/auth/refresh'){
return false;
}
return new Promise(async (resolve, reject) => {
const token = store.getState().app.token;
//Check if token has expired:
if (token && Date.now() / 1000 >= jwtDecode(token).exp) {
try{
//Token has expired - trigger method below to send a refresh request and save the new token
await refreshToken(token);
} catch(error){
reject(error); // error is caught here but is undefined
}
}
//Only when everything is finished resolve the requst config and let other requests pass
resolve(config);
});
}
async function refreshToken(prevToken) {
//Trying to send the request (The destructiring is not the issue)
const { data : { access_token } } = await api({
url: '/auth/refresh',
method: 'post',
headers: {
Authorization: `Bearer ${prevToken}`
}
});
//I never get here
api.defaults.headers.common.Authorization = `Bearer ${access_token}`;
setItem('token', access_token);
store.dispatch(setToken(access_token));
return access_token;
}
从不发送刷新请求,并且引发异常。谁能告诉我为什么会这样?
我还尝试在refreshToken函数中执行以下操作:
这有效:
async function refreshToken(prevToken) {
const data = await new Promise(resolve => {
setTimeout(() => {
resolve('foo');
}, 1000);
});
return data;
}
这不起作用:
async function refreshToken(prevToken) {
const { data } = await api({
method: 'post',
url: 'https://jsonplaceholder.typicode.com/posts',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
data: {
title: 'foo',
body: 'bar',
userId: 1
}
});
return data;
}
因此,此拦截器设置肯定存在问题,甚至无法启动axios请求。
谢谢