每次致电一次未经授权-401错误,但是一旦我刷新页面

发布于 2025-02-11 08:36:48 字数 1438 浏览 1 评论 0原文

每次我致电用户API时,我都会收到未经授权的错误,但是在我刷新页面

1之后,它起作用。这是我的获取用户方法

import { useContext, useEffect, useState, useCallback } from "react";
import jwtDecode from "jwt-decode";

import AuthContext from "../../store/auth-context";
import { getUserInfo } from "../../lib/api";



const Products = () => {
  const authCtx = useContext(AuthContext);
  const decodedToken = jwtDecode(authCtx.contextValue.token);
  const userData = decodedToken.data.userData;


  const fetchUserInfo = useCallback(async () => {
    setIsLoading(true);
    getUserInfo(userData.id).then((response) => {
      let groupId = response.data[0].work_group;
      setIsLoading(false);
    });
  }, []);

  useEffect(() => {
    fetchUserInfo();
  }, []);

2。这是我的用户API调用

export async function getUserInfo(userId) {
  let token = localStorage.getItem('token');
  const response = await fetch(`${CODE_CORP_API}/users/${userId}`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization" : `Bearer ${token}`
    },
  });
  const data = await response.json();
  if (!response.ok) {
    throw new Error(data.message || "Could not create account.");
  }
  return data;
}

Each time I call the user API, I get an unauthorised error, but it works after I have refreshed the page

1. This is my fetch user method

import { useContext, useEffect, useState, useCallback } from "react";
import jwtDecode from "jwt-decode";

import AuthContext from "../../store/auth-context";
import { getUserInfo } from "../../lib/api";



const Products = () => {
  const authCtx = useContext(AuthContext);
  const decodedToken = jwtDecode(authCtx.contextValue.token);
  const userData = decodedToken.data.userData;


  const fetchUserInfo = useCallback(async () => {
    setIsLoading(true);
    getUserInfo(userData.id).then((response) => {
      let groupId = response.data[0].work_group;
      setIsLoading(false);
    });
  }, []);

  useEffect(() => {
    fetchUserInfo();
  }, []);

2. This is my user api call

export async function getUserInfo(userId) {
  let token = localStorage.getItem('token');
  const response = await fetch(`${CODE_CORP_API}/users/${userId}`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "Authorization" : `Bearer ${token}`
    },
  });
  const data = await response.json();
  if (!response.ok) {
    throw new Error(data.message || "Could not create account.");
  }
  return data;
}

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文