我有一个使用express api的react应用。访问令牌过期时,我正在尝试刷新令牌。我正在为此使用axios拦截器。
let isRefreshing = false;
let failedQueue = [];
const processQueue = (error, accessToken = null) => {
failedQueue.forEach((prom) => {
if (error) {
prom.reject(error);
} else {
prom.resolve(accessToken);
}
});
failedQueue = [];
};
axiosInstance.interceptors.response.use(
async (response) => {
return response;
},
async (error) => {
const { status, data } = error.response;
const originalRequest = error.config;
if (error.response.status===401 && data.message === "Invalid refresh token") {
console.log("unauthorized");
store.dispatch(authActions.logout());
return;
}
if(error.response.status === 401 && data.message === "You are not authorized to access this route,you don't have a valid refresh token to create new access token "){
console.log("invalid refresh token");
console.log(error.response)
store.dispatch(authActions.logout());
return error.response;
}
if (error.response.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
console.log("isRefreshing");
return new Promise((resolve, reject) => {
console.log("isRefreshing2");
failedQueue.push({ resolve, reject });
})
.then((accessToken) => {
console.log("access")
originalRequest.headers["Authorization"] =
"Bearer:" + accessToken;
console.log("access: " + accessToken);
return axiosInstance(originalRequest);
})
.catch((err) => {
console.log("err");
return Promise.reject(err);
});
}
console.log("no refreshing");
originalRequest._retry = true;
console.log(originalRequest._retry);
isRefreshing = true;
return new Promise((resolve, reject) => {
postMethod("auth/token",null,null).then((result) => {
console.log("result:",result)
setToken(result.data.access_token);
axiosInstance.defaults.headers.common["Authorization"] =
"Bearer:" + result.data.access_token;
originalRequest.headers["Authorization"] =
"Bearer:" + result.data.access_token;
processQueue(null, result.data.access_token);
resolve(axiosInstance(originalRequest));
})
.catch((err) => {
console.log(err.response)
processQueue(err, null);
reject(err);
})
.then(() => {
isRefreshing = false;
});
//TODO:Eğer refresh tokenın da süresi dolmuşsa burda history.push oluyor. ama diğer tarafı bozuyor
});
}
return Promise.reject(error);
}
);
它卡在某个地方。我使用console.log进行调试。 从控制台;
POST http:// localhost:5000 / api / auth / token?null 401(未经授权)
不刷新//它是if语句之后的第一行
POST http:// localhost:5000 / api / auth / token?null 401(未经授权)
isRefreshing //它来自第三条if语句
isRefreshing2 //来自第三条if语句
之后什么也没发生。我该怎么办 ?谢谢您的帮助
答案 0 :(得分:0)
Hond