SyntaxError: Unexpected 令牌 < in JSON
错误信息
Unexpected 令牌 < in JSON at 位置 0
快速摘要
你 called JSON.parse() on 响应那个是 HTML, 不 JSON — 通常 API 错误 page or redirect 到登录 page.
为什么发生
服务器 returned HTML 错误 page 相反的 JSON
获取响应是 redirected 到登录 page (HTML)
响应内容-类型是 不检查之前 parsing
最小示例
✗ 错误代码
const res = await fetch("/api/data");
const data = JSON.parse(await res.text());✓ 修复代码
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();如果服务器返回 HTML (e.g., 404 page), JSON.parse 失败 on < character. 检查 res.好的首先 and use res.JSON().
如何诊断
Log raw 响应文本之前 parsing 到 see 什么是 returned
检查响应状态码 and 内容-类型请求头
验证 API 端点是 正确 and 服务器是 运行
如何修复
检查响应.好的 and 响应状态之前 parsing
验证内容-类型是 application/JSON 之前 calling .JSON()
Handle 非-JSON 响应使用 appropriate 错误消息
如何预防
总是检查响应.好的 and 内容-类型之前 parsing JSON
Use 响应.JSON() 哪个 handles 内容-类型 automatically
Log unexpected 响应 for 调试