fetch 和 axios 的区别
What is the difference between making server requests via fetch and axios?
一句话:fetch 是浏览器内置的, 很基础;axios 是第三方库, 把常用的事都替你做了。
fetch | axios | |
|---|---|---|
| 依赖 | 无,浏览器/Node 18+ 内置 | 要装(约 13 KB) |
| 4xx / 5xx | 不 reject, 要自己查 res.ok | 自动抛错 |
| JSON | 要手动 await res.json() | 自动解析到 data |
| 超时 | 要自己配 AbortController | timeout 一个选项 |
| 拦截器 | 没有,要自己包一层 | 内置(统一加 token、统一处理 401) |
| 上传进度 | 很麻烦 | 支持 |
| Node 里可用 | 18+ 才有 | 一直可以 |
「404 不 reject」是这题的核心考点, 也是真实 bug 的来源:不查res.ok 就会把错误页当数据渲染。从 axios 转过来的人最容易漏这一条, 因为 axios 会自己抛。
怎么选:简单项目、在意包体积、 或者只发几个请求 → fetch包一个自己的小 wrapper; 需要拦截器 / 统一错误处理 / 上传进度,或者要兼容老 Node → axios。
更常见的现实答案:用TanStack Query / SWR管缓存和请求状态, 底下用哪个都行 —— 因为fetch 和 axios都不管缓存、去重、重试。 能这么答说明你想过分层。
In one line: fetch is built into the browser and very bare-bones; axios is a third-party library that does the routine work for you.
fetch | axios | |
|---|---|---|
| Dependency | None, built into browsers and Node 18+ | Must be installed (about 13 KB) |
| 4xx / 5xx | Does not reject; you check res.ok yourself | Throws for you |
| JSON | You call await res.json() by hand | Parsed into data already |
| Timeout | Wire up an AbortController yourself | One timeout option |
| Interceptors | None; wrap it yourself | Built in (attach a token everywhere, handle 401 in one place) |
| Upload progress | Painful | Supported |
| Available in Node | Only from 18 | Always has been |
“404 does not reject” is the heart of this question, and a real source of bugs: skip the res.ok check and you render an error page as if it were data. People coming over from axios miss this one most often, because axios throws on their behalf.
How to choose: a small project, a tight bundle budget, or only a handful of requests → fetch with your own small wrapper. Interceptors, one place for error handling, upload progress, or an old Node to support → axios.
The more realistic answer: reach for TanStack Query or SWR to manage caching and request state, and whichever one sits underneath hardly matters — because neither fetch nor axios handles caching, deduplication or retries. Answering that way shows you have thought about the layers.