我在更新 token 以重新执行原始请求后遇到问题。 基本上,在获取并正确设置新 token 后,当我尝试执行原始请求时,我不断收到请求失败,状态代码为 401。
我确定我搞砸了 promise ,但我无法意识到问题出在哪里
// axiosWrapper.js
import axios from 'axios';
import authenticationApi from './authentication';
const baseURL = 'http://apiurl/';
const axiosWrapper = axios.create({
baseURL,
});
axiosWrapper.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
return authenticationApi.auth()
.then(res => {
if (res.status === 200) {
setToken(res.data.token);
return axios.request(error.config);
}
})
.catch(err => {
console.log(err); // Request failed with status code 401
});
}
return Promise.reject(error);
},
);
axiosWrapper.interceptors.request.use(async config => {
if (config.url === '/auth') {
return config;
}
var token = await getToken();
config.headers.Authorization = token ? 'Bearer ${token}' : '';
return config;
});
export default axiosWrapper;
// authentication.js
import axiosWrapper from './axiosWrapper';
export default {
auth: () => axiosWrapper.post('auth', {apiKey: 'apiKey'}),
};
最佳答案
经过仔细调试和重构,我意识到问题出在我返回的 promise 上,而不是返回新请求的结果。 事实证明,使用 async/await 关键字使它更加清晰。 所以这是重构后的样子:
const baseURL = 'http://server/';
const axiosWrapper = axios.create({
baseURL,
});
axiosWrapper.interceptors.response.use(
response => response,
async error => {
if (error.response.status === 401) {
if (error.config._retry) {
return Promise.reject(error);
}
error.config._retry = true;
const authResult = await authenticationApi.auth()
if (authResult.status === 200) {
await setToken(authResult.data.token); // Set token to storage
error.config.headers.Authorization = `Bearer ${authResult.data.token}`;
const requestResult = await axios.request(error.config);
return requestResult; // Return the result of the request, not the promise
}
}
return Promise.reject(error);
},
);
axiosWrapper.interceptors.request.use(async config => {
if (config.url === 'auth') {
return config;
}
const token = await getToken(); // Get token from storage
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
关于javascript - axios更新token时一直返回401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023805/