React+Node.js项目404错误与JSON解析异常排查求助
问题排查:React+Node项目中的404与JSON解析错误
问题现象
- 请求接口时返回404 Not Found
- 前端抛出
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON异常
核心原因分析
- 404错误:请求的接口路径无效,要么是前端参数拼接错误,要么是后端路由未正确挂载
- JSON解析错误:后端返回了HTML内容(比如404页面、登录跳转页),但前端强行用
resp.json()解析非JSON数据,触发语法错误
具体修复步骤
1. 修复前端参数拼接错误
useParams()返回的是一个对象(格式为{ userId: "xxx" }),直接拼接路径会生成/user/[object Object],这是完全无效的请求路径。
修改UserProfile.js中的参数获取代码:
// 原错误代码 const userId = useParams() // 修改为解构获取具体参数 const { userId } = useParams();
2. 给fetch添加响应状态校验
添加resp.ok判断,在响应异常时直接抛出错误,避免解析非JSON内容:
useEffect(() => { fetch(`/user/${userId}`, { method:"GET", headers: { "Authorization": "Bearer " + localStorage.getItem("token") } }) .then(resp => { if (!resp.ok) { throw new Error(`HTTP请求失败,状态码:${resp.status}`); } return resp.json(); }) .then(result => { setUserProfile(result); }) .catch(err => { console.error('请求失败:', err); // 这里可以添加前端错误提示逻辑 }); }, [userId]); // 添加userId到依赖数组,避免闭包导致的参数过期问题
3. 确认后端路由挂载
检查你的主服务文件(如server.js/app.js)是否正确挂载了user路由:
// 确保存在类似挂载代码 const userRoutes = require('./routes/user'); app.use('/', userRoutes); // 若路由有前缀(如'/api'),则前端请求路径需改为`/api/user/${userId}`
4. 检查requireLogin中间件逻辑
确保中间件在验证失败时返回JSON格式错误,而非HTML页面:
// 示例正确的中间件逻辑 const requireLogin = (req, res, next) => { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: "未授权,请先登录" }); } // 其余token验证逻辑... next(); };
修改后的前端关键代码
const UserProfile = ({ match }) => { const [userProfile, setUserProfile] = useState(null); const { state, dispatch } = useContext(UserContext); const { userId } = useParams(); // 修复参数获取 useEffect(() => { if (!userId) return; // 避免空ID发起无效请求 fetch(`/user/${userId}`, { method:"GET", headers: { "Authorization": "Bearer " + localStorage.getItem("token") } }) .then(resp => { if (!resp.ok) throw new Error(`请求失败,状态码:${resp.status}`); return resp.json(); }) .then(result => { setUserProfile(result); }) .catch(err => { console.error(err); // 可添加UI层面的错误提示 }); }, [userId]); // 其余渲染代码保持不变... };
内容的提问来源于stack exchange,提问作者Sudip S N
相关产品推荐
相关产品推荐

