Unexpected JSON token at offset 11: Expected EOF after parsing, but had h instea...
错误信息
Unexpected JSON token at offset 11: Expected EOF after parsing, but had h instead at path: $ JSON input: <!doctype html> <html lang="en">
<head>.....
AI 解决方案
🔍 错误分析
1. 🌐 错误翻译
原文:Unexpected JSON token at offset 11: Expected EOF after parsing, but had h instead at path: $ JSON input: <!doctype html> <html lang="en">
<head>.....
译文:在偏移量 11 处出现意外的 JSON 标记:在解析后预期为文件结束符(EOF),但实际遇到了字符 'h',位置路径:$,JSON 输入:<!doctype html> <html lang="en">
<head>.....
2. 🎯 原因分析
<html> 标签)3. 💡 解决方案
#### 核心思路
首先检查 HTTP 响应状态码和内容类型,确保接收的是真正的 JSON 数据,而非 HTML 错误页面。以下是常见修复步骤和代码示例:
// 使用 fetch 请求的正确处理方式(JavaScript 示例)
async function fetchJsonData(url) {
try {
const response = await fetch(url);
// 1. 检查响应状态码,非 2xx 状态码可能返回错误页面
if (!response.ok) {
console.error(`HTTP 错误!状态码:${response.status}`);
// 可进一步读取响应内容判断是否为 HTML 错误页
const text = await response.text();
if (text.trim().startsWith('<!doctype html>')) {
throw new Error('服务器返回了 HTML 错误页面,而非预期的 JSON 数据');
}
throw new Error(`请求失败,状态码:${response.status}`);
}
// 2. 检查响应头 Content-Type 是否为 JSON
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
console.warn(`响应类型异常:${contentType}`);
const responseText = await response.text();
console.error(`响应内容(非 JSON): ${responseText.substring(0, 200)}...`);
throw new Error('服务器返回的不是 JSON 类型数据');
}
// 3. 正常解析 JSON
return await response.json();
} catch (error) {
console.error('JSON 解析或请求错误:', error.message);
// 根据业务需求处理错误,例如重试、提示用户等
throw error;
}
}
// 使用示例
fetchJsonData('https://api.example.com/data')
.then(data => console.log('成功获取数据:', data))
.catch(error => console.error('处理失败:', error));
#### 关键修复步骤
2xx(成功状态),非成功状态需处理可能的错误页面Content-Type,确认值为 application/json(或包含 json 标识)再进行解析4. 🛡️ 预防措施
Content-Type 头信息,不直接信任服务器返回的内容直接解析axios、fetch(配合二次封装)、OkHttp(Java)、requests(Python)等成熟库,这类库通常提供响应状态码检查、内容类型处理的便捷方法,减少手动出错概率