Fetch API 获取 JSON 需先调用 response.json() 解析且仅能调用一次,应先检查 response.ok 或 status 确保 2xx 状态,推荐用 async/await + try/catch 处理错误,并注意 Content-Type 和非标准响应容错。

Fetch API 返回的 JSON 数据需要先调用 response.json() 方法解析,再通过 Promise 链或 async/await 处理结果,不能直接使用响应体对象。
确保响应状态正常再解析 JSON
HTTP 状态码非 2xx 时,fetch 不会自动抛错,但 response.json() 仍可能执行,导致后续逻辑出错。建议先检查 response.ok 或 response.status:
-
response.ok为true表示状态码在 200–299 范围内 - 若失败,可手动抛出错误,便于
catch或try/catch统一处理
用 async/await 写法更清晰(推荐)
避免嵌套 Promise,代码可读性高,错误处理也直观:
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); // 必须 await,因为 .json() 返回 Promise
console.log(data);
} catch (err) {
console.error('请求或解析失败:', err.message);
}
}
注意 .json() 只能调用一次
response.json() 消耗响应体流,重复调用会报错 TypeError: Already read。如需多次使用数据:
立即学习“Java免费学习笔记(深入)”;
- 把解析结果保存到变量中复用
- 不要对同一个
response对象多次调用.json()或.text()等读取方法 - 若需多种格式(如同时要 JSON 和原始文本),只能选其一,或用
response.clone()创建副本
后端返回非标准 JSON 时要小心
比如返回空字符串、HTML 错误页、或带 BOM 的 JSON,会导致 .json() 解析失败并拒绝 Promise:
- 服务端应确保 Content-Type 响应头为
application/json - 前端可在
catch中检查err.name === 'SyntaxError'判断是否为 JSON 解析失败 - 必要时用
response.text()获取原始内容,再手动调试或容错处理


















