

新闻资讯
技术学院fetch是浏览器原生API,轻量但需手动处理错误、Cookie、超时等;axios是第三方库,开箱即用,内置拦截器、自动JSON序列化、超时控制等功能,适合中大型项目。
JavaScript 中发起网络请求最常用的是 fetch 和 axios,两者都能发 HTTP 请求,但设计目标、默认行为和使用体验差异明显。选哪个不取决于“谁更好”,而要看项目需求、团队习惯和是否需要额外功能。
fetch 是现代浏览器内置的标准 API,无需安装依赖,语法简洁:
示例:
fetch('/api/users')
.then(res => {
if (!res.ok) throw new Error('网络响应失败');
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
但它有几点必须注意:
catch,需手动检查 res.ok 或 res.status
credentials: 'include'
axios 是基于 XMLHttpRequest(或 Node.js 的 http 模块)封装的库,需通过 npm 安装:npm install axios。它把常见痛点都做了默认处理:
catch
withCredentials: true
fetch 在纯 Node 中不可用,需靠 polyfill 或替代方案)示例:
axios.get('/api/users', {
timeout: 5000,
withCredentials: true
})
.then(res => console.log(res.data))
.catch(err => {
if (err.code === 'ECONNABORTED') console.log('请求超时');
});
fetch 足够,无额外依赖axios 更省心fetc
h 不支持)→ 只能用 axios 或 XMLHttpRequest
axios 的响应泛型更直观(axios.get(...) )fetch 的 Response.body 是 ReadableStream,只能读一次;多次读取需用 res.clone()
axios 默认 Content-Type 是 application/json,发表单要用 FormData 并手动设 headerAccess-Control-Allow-Origin 等头