Unexpected token < in JSON at position 0. 请给出详细排查步骤和多个修复代码示例,回答尽量详细完整。
错误信息
SyntaxError: Unexpected token < in JSON at position 0. 请给出详细排查步骤和多个修复代码示例,回答尽量详细完整。
AI 解决方案
1. 🌐 错误翻译
原文:SyntaxError: Unexpected token < in JSON at position 0
译文:语法错误:在JSON的第0个位置出现意外的符号 <
2. 🎯 原因分析
根本原因:
当尝试解析JSON数据时,解析器期望接收到以
{(对象)或[(数组)开头的有效JSON格式,但实际接收到的数据以<开头,这通常是HTML标签的起始符号。发生场景:
具体表现:
JSON.parse()时,传入的字符串以<开头fetch或axios获取响应后调用response.json(),但响应内容是HTML3. 💡 解决方案
场景一:使用 fetch 获取JSON数据
错误代码:
fetch('/api/user/123')
.then(response => response.json()) // 直接解析,未检查响应状态
.then(data => console.log(data))
.catch(error => console.error(error));
修复方案:添加响应状态检查和内容类型验证
fetch('/api/user/123')
.then(response => {
// 检查HTTP状态码,非2xx会抛出错误
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 检查响应头是否为JSON类型(可选,增强健壮性)
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error(`Expected JSON but got ${contentType}`);
}
return response.json();
})
.then(data => console.log('成功获取数据:', data))
.catch(error => console.error('请求失败:', error));
场景二:使用 axios 获取JSON数据
错误代码:
axios.get('/api/user/123')
.then(response => {
console.log(response.data); // 假设response.data是JSON,但实际是HTML
})
.catch(error => console.error(error));
修复方案:检查响应数据类型和HTTP状态
``javascript请求失败,状态码:${response.status}`);
axios.get('/api/user/123')
.then(response => {
// 检查HTTP状态码
if (response.status !== 200) {
throw new Error(
}
// 检查响应数据类型
const isJson = typeof response.data === 'object' ||
(typeof response.data === 'string' && response.data.trim()[0] === '{');
if (!isJson)