Fetch API 默认不校验 HTTP 状态码,404/500 等仍会 resolve,需手动检查 response.ok 或 status;无默认超时、不自动解析 JSON、不带凭据,错误处理分网络失败、HTTP 异常、解析失败三层。

Fetch API 是现代 JavaScript 中发起网络请求的首选方式,它比 XMLHttpRequest 更简洁、更符合 Promise 语义,且原生支持 async/await。但直接用 fetch() 容易忽略错误处理和状态判断——它只在 ** 网络失败 **(如断网、DNS 错误)时拒绝 Promise,而 404、500 这类 HTTP 错误仍会进入 then() 分支。
fetch() 默认不校验 HTTP 状态码
这是最常踩的坑:调用 fetch('/api/user') 返回 401 响应时,Promise 依然 resolve,你得手动检查 response.ok 或 response.status。
-
response.ok是布尔值,等价于response.status >= 200 && response.status - 如果后端返回
204 No Content,response.body为空,response.json()会抛错,需先判断response.headers.get('content-type')?.includes('json') - 默认不带 Cookie,跨域请求需显式传
{credentials: 'include'},否则服务端收不到 session
const res = await fetch('/api/profile'); if (!res.ok) {throw new Error(`HTTP ${res.status}: ${res.statusText}`); } const data = await res.json();
POST 请求要配对设置 Content-Type 和 body
发送 JSON 数据时,Content-Type 头和 body 格式必须匹配,否则后端可能解析失败或 400 报错。
- 发 JSON:设
headers: {'Content-Type': 'application/json'},且body: JSON.stringify({name: 'Alice'}) - 发表单数据:用
new URLSearchParams({name: 'Alice'}),此时不要手动设Content-Type,浏览器 会自动加application/x-www-form-urlencoded - 传文件:用
FormData对象,此时也不能手动设Content-Type,否则会破坏 boundary
await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json'}, body: JSON.stringify({email: 'a@b.c', password: '123'}) });
如何取消 fetch 请求(AbortController)
原生 fetch() 不支持超时或手动取消,但可通过 AbortController 实现。尤其在 React 组件卸载、用户快速切换页面时,避免内存泄漏和无意义的响应处理。
立即学习“Java 免费学习笔记(深入)”;
- 创建
const controller = new AbortController(),把controller.signal传入fetch()的signal选项 - 调用
controller.abort()后,fetch()会立即 reject,错误类型是DOMException,name === 'AbortError' - 超时控制可结合
setTimeout(() => controller.abort(), 8000)
const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); try {const res = await fetch('/api/slow', { signal: controller.signal}); } catch (err) {if (err.name === 'AbortError') {console.log('Request timed out or aborted'); } }
与 axios 等库的关键差异点
如果你从 axios 迁移过来,注意这些行为差异:
-
fetch()没有默认超时,没有自动 JSON 解析,没有请求 / 响应拦截器 -
fetch()不会自动带上凭据(Cookie),credentials: 'same-origin'才是安全默认 -
response.json()只能调用一次,因为ReadableStream被消费后不可重读;需要多次读取时,先用response.clone() - 错误处理粒度更细:网络层错误(reject)、HTTP 状态异常(需手动判断)、JSON 解析失败(
res.json()reject)是三层独立问题
真正用好 fetch() 不在于写几行代码,而在于始终记得它只是“发送并接收原始响应”,所有业务逻辑(重试、鉴权、缓存、错误映射)都得自己补全。别指望它像封装库一样开箱即用。






























