REACT异步函数返回未定义的

发布于 2025-02-13 18:10:11 字数 1916 浏览 1 评论 0原文

我有一个React Hook,可以在每个页面上调用刷新。

挂钩是这样的:


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中的令牌,即使服务器响应:

{"msg":"AUTHORIZATION SUCCESSFUL","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyVUlEIjoiZmZaTUZTTDF4UGNXdFQ5MDJkd2Z6RFB1WElEMyIsInBvc2l0aW9uIjoibWFuYWdlciIsImNvbXBhbnlJRCI6Ik14Z1ZleEhlSGZzN29ndTJaMm10IiwiaWF0IjoxNjU3MTQyMDU5LCJleHAiOjE2NTcxNDkyNTl9.l9OHl-84S5LrwF1r0fqQl2zuHhS-hrWaFj8QjrxDgQA"}

我不确定为什么我的代码不等待API响应来更新令牌。

附加信息:我每次加载它们时至少要调用刷新的页面至少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);
};

I have a React Hook that calls the Refreshtoken on each page.

the Hook is this :


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;

but every time it runs it sets my token in the localstorage to undefined even with the server responding with the actual updated token:

{"msg":"AUTHORIZATION SUCCESSFUL","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyVUlEIjoiZmZaTUZTTDF4UGNXdFQ5MDJkd2Z6RFB1WElEMyIsInBvc2l0aW9uIjoibWFuYWdlciIsImNvbXBhbnlJRCI6Ik14Z1ZleEhlSGZzN29ndTJaMm10IiwiaWF0IjoxNjU3MTQyMDU5LCJleHAiOjE2NTcxNDkyNTl9.l9OHl-84S5LrwF1r0fqQl2zuHhS-hrWaFj8QjrxDgQA"}

I'm not sure why is my code not waiting for the API response to update the token.

Additional info: the page I'm on calls the refreshToken at least 3 times every time I load them.

If someone could shed some light on me I would be grateful.

Edit:

refreshToken() is this call to the 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);
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七度光 2025-02-20 18:10:11

我认为,因为LocalStorage将您的令牌设置为刷新令牌返回。您可以尝试将window.localstorage.setItem(“ token”,ntoken);置于refreshtoken()的响应中。如果它无法正常工作。

    const ntoken = await refreshToken().then((obj) => {
        window.localStorage.setItem("token", ntoken);
        return obj.token;
      });          

I think because localStorage set your token before your refresh token return. You can try put window.localStorage.setItem("token", ntoken); into response of refreshtoken(). If it does not work console.log your obj return may be there miss spell of token

    const ntoken = await refreshToken().then((obj) => {
        window.localStorage.setItem("token", ntoken);
        return obj.token;
      });          

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文