Invalid JSON response
错误信息
Invalid JSON response
AI 解决方案
报错分析报告
1.错误翻译
原文:Invalid JSON response
译文:无效的JSON响应
2. 原因分析
JSON.parse()、json.loads()等),或接口返回数据的校验环节。3.解决方案
以JavaScript(Fetch API)为例,添加响应验证与错误捕获:
async function safeParseJson(url) {
try {
const res = await fetch(url);
const rawText = await res.text(); // 先读取原始文本(用于调试)
// 验证Content-Type(可选但推荐)
if (!res.headers.get('content-type')?.includes('application/json')) {
throw new Error(`非JSON响应,原始内容:${rawText.slice(0, 100)}`);
}
return JSON.parse(rawText); // 安全解析
} catch (err) {
console.error('JSON解析失败:', err.message);
console.debug('原始响应:', rawText); // 调试用
return null; // 或抛出自定义错误
}
}
若需后端修复(以Node.js/Express为例),确保返回标准JSON:
app.get('/api/data', (req, res) => {
try {
const data = { code: 200, result: 'success' };
res.setHeader('Content-Type', 'application/json'); // 明确类型
res.send(JSON.stringify(data)); // 或用res.json(data)自动处理
} catch (err) {
res.status(500).json({ code: 500, error: '服务器内部错误' }); // 错误也返回JSON
}
});
4. 预防措施
Content-Type: application/json响应头。 try-catch包裹逻辑,优先读取原始文本调试;用Postman等工具预检查接口返回。 推荐工具:Postman(接口测试)、JSONLint(JSON校验)、VS Code JSON插件(实时语法检查)。