fetch需await或.then处理Promise,HTTP错误需手动检查response.ok,JSON数据须调用response.json()并await,POST请求必须设置Content-Type并字符串化body。

用 fetch 发送请求本身很简单,但实际项目中出错多是因为没处理好异步链、错误分支或响应体解析逻辑。
fetch 基本调用必须用 await 或 .then() 链式处理
fetch 返回的是 Promise,不 await / 不接 .then() 就拿不到数据,也捕获不到网络错误。
- 常见错误:写了
fetch('/api/user')但没等它完成,直接去读response.data—— 此时response还是 Promise 对象,不是真实响应 - 正确做法:要么用
async/await(推荐),要么确保每个fetch后都跟.then(res => res.json())这类解析步骤 - 注意:
fetch只在网络失败(如断网、DNS 失败)时 reject;HTTP 状态码 404、500 不会触发 catch,得手动检查response.ok
获取 JSON 数据要显式调用 response.json()
fetch 返回的 Response 对象不是直接可用的数据,必须调用它的解析方法才能拿到 JS 对象。
-
response.json()返回另一个 Promise,需再次 await 或 .then - 其他常用解析方法:
response.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);
}
}
POST 请求要配 headers 和 body,且注意格式
GET 请求靠 URL 传参,POST 则需手动设置请求头和请求体,否则后端很可能收不到数据或解析失败。
立即学习“前端免费学习笔记(深入)”;
- 发送 JSON 数据时,
headers必须包含'Content-Type': 'application/json' -
body必须是字符串(用JSON.stringify()),不能直接传对象 - 如果后端期望表单数据(
application/x-www-form-urlencoded),要用URLSearchParams构造 body - 忘记设
Content-Type是最常被忽略的点,会导致后端收到空 body
fetch('/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”,但根本原因藏得很深。











