Unexpected token '<', "<!DOCTYPE "... is not valid JSON
错误信息
Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
AI 解决方案
报错分析报告
错误翻译
原文:Unexpected token '<', "<!DOCTYPE "... is not valid JSON
译文:意外的标记'<',"<!DOCTYPE "... 不是有效的JSON
原因分析
这是一个典型的JSON解析错误。当代码期望接收JSON格式的数据时,实际上却收到了HTML内容(通常是错误页面)。
根本原因:
错误位置:通常在fetch().then(response => response.json())或类似的数据解析代码处。
解决方案
方案1:检查响应状态(推荐)
fetch('https://api.example.com/data')
.then(response => {
// 首先检查响应状态
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
// 检查Content-Type是否为JSON
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('服务器未返回JSON格式数据');
}
return response.json();
})
.then(data => {
// 处理数据
console.log(data);
})
.catch(error => {
console.error('请求失败:', error);
// 显示用户友好的错误信息
});
方案2:使用try-catch处理解析错误
fetch('https://api.example.com/data')
.then(response => response.text()) // 先获取文本
.then(text => {
try {
const data = JSON.parse(text);
// 处理数据
console.log(data);
} catch (error) {
console.error('JSON解析失败:', error);
console.log('服务器返回的内容:', text.substring(0, 200)); // 查看前200字符
}
})
.catch(error => {
console.error('请求失败:', error);
});
##️ 预防措施
1. 添加响应验证
response.ok或response.statusapplication/json类型2.️ 开发建议
推荐工具:
下次遇到类似错误时,先检查网络请求的原始响应内容,这能快速定位问题根源。