模型检测异常:Unexpected token '<', "<!DOCTYPE "... is not valid JSON
错误信息
模型检测异常:Unexpected token '<', "<!DOCTYPE "... is not valid JSON
AI 解决方案
报错分析报告
1.错误翻译
原文:Unexpected token '<', "<!DOCTYPE "... is not valid JSON
译文:意外的字符'<', "<!DOCTYPE "..."不是有效的JSON
2. 原因分析
<!DOCTYPE声明),JSON解析器无法识别<字符。 JSON.parse())处理HTTP响应体时,响应内容为HTML而非JSON。3.解决方案
// 修复后的代码示例(以Fetch API为例)
async function fetchData(url) {
try {
const response = await fetch(url);
// 1. 检查响应状态
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
// 2. 验证Content-Type是否为JSON
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error(`Expected JSON, got ${contentType}`);
}
// 3. 安全解析JSON
const data = await response.json();
return data;
} catch (error) {
console.error('请求失败:', error.message);
// 处理错误(如返回默认数据/提示用户)
}
}
4. 预防措施
Accept: application/json头,明确要求JSON响应;解析前验证Content-Type。 try/catch包裹JSON解析逻辑,捕获并处理解析失败场景。 ---
注:若需分析其他报错,请提供具体错误信息。