fetch需await或.then处理Promise,HTTP错误需手动检查response.ok,JSON数据须调用response.json()并await,POST请求必须设置Content-Type并字符串化body。
用 fetch 发送请求本身很简单,但实际项目中出错多是因为没处理好异步链、错误分支或响应体解析逻辑。
await 或 .then() 链式处理fetch 返回的是 Promise,不 await / 不接 .then() 就拿不到数据,也捕获不到网络错误。
fetch('/api/user') 但没等它完成,直接去读 response.data —— 此时 response 还是 Promi
async/await(推荐),要么确保每个 fetch 后都跟 .then(res => res.json()) 这类解析步骤fetch 只在网络失败(如断网、DNS 失败)时 reject;HTTP 状态码 404、500 不会触发 catch,得手动检查 response.ok
response.json()
fetch 返回的 Response 对象不是直接可用的数据,必须调用它的解析方法才能拿到 JS 对象。
response.json() 返回另一个 Promise,需再次 await 或 .thenresponse.text()(纯字符串)、response.blob()(文件下载)、response.arrayBuffer()(二进制)const data = await fetch('/api/user').json() —— fetch() 本身没有 json() 方法,会报 TypeError: fetch(...).json is not a function
async function getUser() {
try {
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); // 必须 await 这一步
return data;
} catch (err) {
console.error('Fetch failed:', err);
}
}
headers 和 body,且注意格式GET 请求靠 URL 传参,POST 则需手动设置请求头和请求体,否则后端很可能收不到数据或解析失败。
headers 必须包含 'Content-Type': 'application/json'
body 必须是字符串(用 JSON.stringify()),不能直接传对象application/x-www-form-urlencoded),要用 URLSearchParams 构造 bodyContent-Type 是最常被忽略的点,会导致后端收到空 bodyfetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'admin', password: '123' })
});
真正容易卡住的地方不在语法,而在 response 状态判断、JSON 解析时机、以及 POST 的 content-type 匹配——这三处任一漏掉,控制台可能只显示 “undefined” 或 “Unexpected end of JSON input”,但根本原因藏得很深。