每次致电一次未经授权-401错误,但是一旦我刷新页面
每次我致电用户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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论