fetch 比 XMLHttpRequest 更直接现代,基于 Promise 适配 async/await;需手动检查 response.ok 处理 HTTP 错误;POST 要设 Content-Type;JSON 响应须调用 response.json();忽略 catch 会导致静默失败。
fetch 发起请求比 XMLHttpRequest 更直接现代浏览器中,fetch 是发起 AJAX 请求的首选方式,它基于 Promise,天然适配 async/await。不用手动管理 readyState 和 onreadystatechange,也不用封装回调嵌套。
常见错误是忽略网络失败和 HTTP 错误的区别:fetch 只在“网络异常”时 reject(比如断网、DNS 失败),而 404、500 这类响应仍会 resolve,需手动检查 response.ok 或 response.status。
Content-Type,否则后端可能收不到 body
response.json(),它本身也返回 Promisecatch 或 try/catch 会导致静默失败(尤其在 async 函数里)async function getUser() {
try {
const response = await fetch('/api/user/123');
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (err) {
console.error('请求失败:', err.message);
}
}
async/await 是处理异步回调最清晰的方式把回调地狱(callback hell)换成 async/await,逻辑就变成“像写同步代码一样”,但执行仍是异步的。关键点在于:所有 await 后面必须是 Promise,普通值会被自动包装;函数本身必须用 async 声明,否则语法报错。
容易踩的坑是误以为 await 能“阻塞整个脚本”——它只暂停当前 async 函数的执行,不影响事件循环,其他任务(如定时器、用户点击)照常运行。
Promise.all([p1, p2]) 并发发,别串着 await
await p().catch(() => null) 或包装成 [data, err] = await to(p()) 模式await,除非你确实要串行;否则用 map().map(p => p.then(...))
XMLHttpRequest?注意三个兼容性雷区IE10+ 支持 XMLHttpRequest,但默认不支持 Promise,且部分行为和 fetch 不一致。如果你必须维护老代码,这几个点必须手动处理:
xhr.responseType = 'json' 在 IE11 下无效,得用 JSON.parse(xhr.responseText)
xhr.timeout 需配合 xhr.ontimeout,不能只靠 onerror
withCredentials 支持不稳定,跨域带 cookie 时优先考虑 fetch + credentials: 'include'
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.responseType = 'text'; // IE 安全写法
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const data = JSON.parse(xhr.response);
console.log(data);
} catch (e) {
console.error('JSON 解析失败');
}
}
};
xhr.send();
catch,还要区分网络层和业务层一个真实的请求链路包含至少三层:网络连接(DNS、TCP、TLS)、HTTP 协议(状态码)、业务语义(比如 { code: 40001, msg
: 'token 过期' })。只用 try/catch 捕获 Promise rejection,会漏掉 HTTP 成功但业务失败的情况。
建议统一在请求封装层做分层判断:先看 response.ok,再看 data.code,最后才抛出业务错误。这样上层调用方可以用一个 catch 处理所有异常,而不必到处写 if (res.data.code !== 0)。
code 字段)时,前端解析前先做 hasOwnProperty 或可选链 ?.code 校验TypeError: Failed to fetch)无法被 response.status 捕获,必须靠 catch