fetch默认不带Cookie、不自动抛错、无超时,需手动处理credentials、res.ok校验及AbortController;axios则默认更友好但响应数据在response.data中。
fetch 是浏览器原生 API,不用额外安装,但默认不带 Cookie、不自动抛错、不支持超时——这些都得手动处理。
最简 GET 请求看起来干净,但实际项目里几乎 always 需要配置 credentials 和错误判断:
fetch('/api/user', {
method: 'GET',
credentials: 'include', // 不加这句,跨域请求不会带 cookie
headers: {
'Accept': 'application/json'
}
})
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch 不会因 4xx/5xx 自动 rej
ect
return res.json();
})
.catch(err => console.error('请求失败:', err));
res.ok 只判断状态码是否在 200–299,401、500 都算“成功”返回,必须手动检查headers['Content-Type'] = 'application/json' 和 body: JSON.stringify(data)
AbortController 控制(见下一条)fetch 本身不支持 timeout 参数,得靠 AbortController 配合 Promise.race 模拟:
function fetchWithTimeout(url, options = {}, timeout = 5000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
return fetch(url, { ...options, signal: controller.signal })
.finally(() => clearTimeout(id));
}
// 使用
fetchWithTimeout('/api/data', { method: 'POST', body: JSON.stringify({x:1}) })
.then(res => res.json())
.catch(err => {
if (err.name === 'AbortError') console.error('请求超时');
else console.error('其他错误:', err);
});
controller.abort() 触发后,fetch Promise 会以 AbortError 拒绝,不是网络错误或 HTTP 错误.finally 清掉定时器,否则可能内存泄漏signal 在 Node.js(v18+)也支持,但老版不兼容axios 默认发送 Content-Type: application/json(对 JS 对象)、自动转换响应体、自带超时、默认携带 cookie(同源时),适合快速落地。
但要注意它把响应数据包在 response.data 里,不是直接返回解析后的结果:
axios.get('/api/profile')
.then(response => {
console.log(response.data); // ✅ 正确:后端返回的 JSON 已自动解析
console.log(response.status); // ✅ 状态码
console.log(response.headers); // ✅ 响应头
})
.catch(error => {
if (error.code === 'ECONNABORTED') console.log('请求超时');
else if (error.response) console.log('HTTP 错误:', error.response.status);
else console.log('网络错误:', error.message);
});
axios.defaults.timeout = 10000 可全局设超时,比 fetch 每次写 AbortController 省事axios.interceptors.request.use)适合统一加 token,但别在其中 throw 错误,否则会中断整个链路axios.create() 配一堆重复 config,除非真有多个不同 base URL 的服务不是“哪个更好”,而是“当前项目卡在哪”:
fetch + 封装一层工具函数(比如加超时、自动 res.json()、统一错误格式)axios 省三天调试时间真正容易被忽略的是:无论用哪个,**HTTP 状态码语义、重试策略、错误降级 UI、Loading 状态边界**,这些从来不在 fetch 或 axios 的 API 里,得你自己串起来。