调用 .json() 方法获取 json 数据,需 await 或 .then() 处理;先检查 content-type 是否为 application/json,再验证 res.ok,最后用 try/catch 捕获网络、解析及业务异常。

Fetch 请求接口后,要拿到 JSON 数据,关键在于调用 .json() 方法 —— 它返回一个 Promise,需用 await 或 .then() 处理。
确保响应体是 JSON 格式
不是所有接口都返回 JSON,先检查 response.headers.get('content-type') 是否包含 application/json。如果接口返回的是纯文本、HTML 或空响应,直接调用 .json() 会报错。
- 服务端未设置
Content-Type: application/json时,.json()仍可能成功(只要内容可解析),但不推荐依赖此行为 - 遇到
Unexpected end of JSON input错误,大概率是响应为空或格式错误,建议先用response.text()查看原始内容
正确链式调用 .json()
fetch() 返回的是 Response 对象,不是数据本身。.json() 是异步方法,必须等待它解析完成才能拿到 JS 对象。
- 使用 async/await(推荐):
const res = await fetch('/api/user');
const data = await res.json(); // 注意这里要 await - 使用 .then():
fetch('/api/user')
.then(res => res.json())
.then(data => console.log(data));
别忘了检查响应状态
res.json() 不会自动拒绝 HTTP 错误状态(如 404、500),需要手动判断 res.ok 或 res.status。
-
res.ok为 true 表示状态码在 200–299 范围内 - 常见写法:
const res = await fetch('/api/user');
if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
const data = await res.json();
错误处理要覆盖全链路
网络失败、JSON 解析失败、业务逻辑异常都可能发生,建议用 try/catch 包裹整个流程。
- 捕获网络错误(如域名不可达、断网)
- 捕获
.json()抛出的语法错误(如返回了 HTML 错误页) - 示例:
try {
const res = await fetch('/api/user');
if (!res.ok) throw new Error(res.statusText);
const data = await res.json();
console.log(data);
} catch (err) {
console.error('请求失败:', err.message);
}
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











