




fetch 是 JavaScript 与后端 API 交互的核心,返回 Promise 需用 .then() 或 async/await 处理;它不因 HTTP 错误状态码(如 404、500)自动 reject,须手动检查 response.ok。
JavaScript 与后端 API 交互的核心是 fetch,不是 XMLHttpRequest,也不是第三方库(除非你有明确兼容性或功能需求)。
fetch 发送 GET 请求并读取 JSON 响应现代浏览器中,fetch 是最轻量、最标准的选择。它返回 Promise,必须用 .then() 或 async/await 处理;且 fetch 不会在 HTTP 状态码异常(如 404、500)时自动 reject,这点极易踩坑。
常见错误现象:Uncaught (in promise) TypeError: Failed to fetch(网络失败)、或静默拿到 500 响应却没报错。
response.ok(即 status >= 200 && status ),再调用 response.json()
response.json() 本身可能 reject(比如返回了非 JSON 内容),需单独 try/catchcatch —— 网络中断、CORS 拒绝、DNS 失败都会触发async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('获取用户失败:', err.message);
throw err;
}
}
POST 不只是“发数据”,关键在于设置正确的请求头和序列化体。后端通常期望 Content-Type: application/json,而 fetch 默认不设任何 header,也不会自动 JSON.stringify。
headers: { 'Content-Type': 'application/json' }
body 必须是字符串,传对象会报错:TypeError: Request with GET/HEAD method cannot have body(其实是 body 类型不对)application/x-www-form-urlencoded),要用 new URLSearchParams(data) 而不是 JSON.stringify
async function createUser(userData) {
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
if (!res.ok) throw new Error(`创建失败: ${res.status}`);
return res.json();
}
带认证的请求常失败,不是因为代码写错,而是服务端未正确配置 CORS 响应头,或前端漏传凭证。
Authorization header:headers: { Authorization: 'Bearer ' + token }
Authorization),fetch 必须显式设 credentials: 'include',否则浏览器
Response to preflight request doesn't pass access control check)是服务端问题,前端无法绕过;但可确认是否误发了非简单请求(如自定义 header、非 GET/POST 方法)触发了预检axios 而不是原生 fetch
不是“更好”,而是“更省事”——当你反复处理重复逻辑时:axios 自动序列化 JSON、自动抛出 HTTP 错误、支持请求/响应拦截器、取消请求(AbortController 在 fetch 中需要手动传)、统一错误结构。
useAxios(@vueuse/core)能简化很多样板axios 反而增加包体积(约 5 kB gzipped),得不偿失fetch 的 AbortController 支持是完整的,但写法比 axios.cancelToken(已废弃)或 CancelToken.source() 更啰嗦真正容易被忽略的点:HTTP 缓存行为。GET 请求默认可被浏览器缓存,导致重复调用返回旧数据;必要时加时间戳参数或设置 cache: 'no-store',别等线上出 bug 才想起来查 Network 面板里的 “from disk cache”。