React项目调用API获取用户数据时出现401 Unauthorized错误
问题场景
开发React应用时,通过useEffect钩子调用后端/user/profile接口获取用户资料,localStorage中已存在token,但请求始终返回401 Unauthorized错误,核心代码如下:
import React, { useState, useEffect } from 'react'; const Dashboard = () => { const [profile, setProfile] = useState({ firstName: '', lastName: '', email: '', phoneNumber: '', address: '', city: '', country: '', zip: '', }); useEffect(() => { const fetchProfile = async () => { const token = localStorage.getItem('token'); if (!token) { console.error('No token found'); return; // Handle the lack of token (redirect to login page or display a message) } try { const response = await fetch('http://localhost:8000/user/profile', { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, }, }); if (response.ok) { const data = await response.json(); setProfile(data); // Update the profile state with the fetched data } else { console.error('Failed to fetch profile:', response.status); // Handle unauthorized access, e.g., redirect to login page } } catch (error) { console.error('Error fetching profile:', error); } }; fetchProfile(); }, []); return ( <div> {/* Profile rendering logic */} </div> ); }; export default Dashboard;
排查与解决步骤
校验Token格式与完整性
在控制台打印console.log('Token:', token),确认token没有多余空格、换行或引号,且Bearer ${token}的格式完全符合后端要求(注意Bearer与token之间必须有一个空格)。验证Token有效性
用JWT解码工具(或jwt-decode库)解析token,检查:exp字段(过期时间)是否已过期,若过期需重新登录获取新token;aud(受众)、iss(发行方)是否与后端配置一致;- token签名算法是否与后端匹配(如HS256/RS256)。
检查请求头发送情况
打开浏览器Network面板,查看请求Headers:- 确认Authorization头是否被正确发送,是否因CORS策略被拦截;
- 部分后端对请求头大小写敏感,尝试将
Authorization改为小写authorization; - 若后端要求,添加
Content-Type: application/json头(部分严格后端会校验GET请求的头信息)。
排查后端鉴权逻辑
查看后端日志,确认:- 后端是否正确从Authorization头中提取token;
- token验证密钥是否与前端一致;
- 当前用户是否拥有访问
/user/profile接口的权限(部分401是权限不足而非token无效)。
确认Token存储正确性
检查登录逻辑中存储token的代码,确保是直接存储接口返回的token值,而非嵌套字段(如response.data.token而非response.data.user.token),避免存储错误内容。增强错误信息获取
在错误处理中添加详细信息打印,便于定位后端返回的具体原因:else { const errorDetails = await response.json(); console.error('Backend error info:', errorDetails); }
内容的提问来源于stack exchange,提问作者Cyborg sonny
相关产品推荐
相关产品推荐

