我有一个React Hook,在每个页面上调用Refreshtoken。
钩子是这样的:
const refresh = async (refToken) => {
try {
if (refToken && !functionalities.isTokenExpired(refToken)) {
const ntoken = await refreshToken().then((obj) => {
return obj.token;
});
window.localStorage.setItem("token", ntoken);
} else {
window.localStorage.clear();
toast.error("O seu acesso expirou! Faça novamente o login no sistema.");
return false;
}
} catch (error) {
toast.error("Não foi possível atualizar o token do usuário");
}
};
async function useRefreshToken() {
const refToken = localStorage.getItem("refreshToken") || "";
if (refToken && !functionalities.isTokenExpired(refToken)) {
refresh(refToken).then(() => {});
// setInterval(() => {
// refresh(refToken).then();
// }, 3564000);
}
}
// 0,99hrs 3564000 - 10min 600000 --
export default useRefreshToken;
但是每次它运行时,它都会将我在localstorage中的令牌设置为undefined,即使服务器响应的是实际更新的令牌:
{"msg":"AUTHORIZATION SUCCESSFUL","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyVUlEIjoiZmZaTUZTTDF4UGNXdFQ5MDJkd2Z6RFB1WElEMyIsInBvc2l0aW9uIjoibWFuYWdlciIsImNvbXBhbnlJRCI6Ik14Z1ZleEhlSGZzN29ndTJaMm10IiwiaWF0IjoxNjU3MTQyMDU5LCJleHAiOjE2NTcxNDkyNTl9.l9OHl-84S5LrwF1r0fqQl2zuHhS-hrWaFj8QjrxDgQA"}
我不知道为什么我的代码不等待API响应来更新令牌。
附加信息:我所在的页面在每次加载它们时至少调用refreshToken 3次。
如果有人能指点一下我,我会很感激的。
编辑:
refreshToken()是对API的调用:
export const refreshToken = async () => {
const headers = getDefaultHeaders(true);
const refToken = localStorage.getItem("refreshToken");
const body = {
refreshToken: refToken,
};
return await axios.post(`${url}/auth/refreshToken`, body, headers);
};
我认为是因为localStorage在刷新令牌返回之前设置了令牌。您可以尝试将window.localStorage.setItem("token", ntoken);
放入refreshtoken()的响应中。如果它不工作控制台日志你的obj
返回可能有错过法术的token
const ntoken = await refreshToken().then((obj) => {
window.localStorage.setItem("token", ntoken);
return obj.token;
});