使用 fetch() 发起请求后,调用返回 promise 的 .json() 方法即可获取接口返回的 json 数据。该方法会自动解析响应体中的 json 字符串并返回一个包含解析后数据的 promise,开发者只需在异步函数中使用 await 等待结果或在 .then() 中处理即可。

如何处理 fetch 请求中的网络错误与 HTTP 状态码
fetch() 仅在发生网络故障(如断网)时才会拒绝 Promise,而不会因 HTTP 404 或 500 等状态码自动报错。因此,必须在调用 .json() 之前检查 response.ok 属性,若为 false 则手动抛出异常,否则后续解析会基于非预期的响应内容(如 HTML 错误页)进行,导致解析失败或逻辑错误。

async function getData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch failed:', error);
}
}
如何验证获取到的 JSON 数据结构是否符合预期
获取到 JSON 数据后,应通过类型检查和属性存在性判断来验证数据结构。由于 .json() 返回的是纯 JavaScript 对象或数组,直接使用 typeof 或 Array.isArray() 确认类型,并检查关键键是否存在,可防止因后端接口变更导致的运行时错误。

async function validateData() {
const response = await fetch('/api/user');
if (!response.ok) return;
const user = await response.json();
if (typeof user !== 'object' || user === null) {
console.error('Invalid data structure');
return;
}
if (!user.id || typeof user.name !== 'string') {
console.error('Missing required fields');
return;
}
console.log('Valid user:', user.name);
}
当接口返回空响应体时 json() 方法的行为是什么
如果接口返回空的响应体(例如 HTTP 204 No Content),调用 .json() 会抛出 SyntaxError,因为无法解析空字符串为有效的 JSON。此时需要在调用 .json() 前检查 response.headers.get('content-length') 或 response.body 的状态,或者捕获该异常以提供默认值。
,
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











