XMLHttpRequest 和 fetch 的区别是什么?
请详细对比 XMLHttpRequest 和 fetch API 在功能、用法和性能上的差异。
回答
我是大山
| 特性 | XMLHttpRequest | fetch |
|---|---|---|
| 编程模型 | 基于事件回调 | 基于 Promise(更现代) |
| 语法简洁性 | 繁琐(需 open/send/事件监听) | 简洁(链式调用) |
| 默认 Cookie | 同域自动携带 | 需 credentials: 'include' |
| 超时设置 | xhr.timeout 直接支持 | 需 AbortController + Promise.race |
| 请求取消 | xhr.abort() | AbortController.abort() |
| 上传进度 | xhr.upload.onprogress | 不支持(需用 XMLHttpRequest) |
| 下载进度 | xhr.onprogress | response.body.getReader() 流式读取 + Content-Length |
| HTTP 错误 | readyState 4 时 status 为 4xx/5xx | 不 reject,需 response.ok 检查 |
| 跨域 | 支持 CORS | 支持 CORS |
| 流式响应 | 不支持 | ✅ 支持 ReadableStream |
| Service Worker | 不支持 | ✅ 可被拦截 |
XMLHttpRequest 示例:
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.timeout = 5000;
xhr.onload = () => console.log(xhr.responseText);
xhr.upload.onprogress = (e) => console.log(e.loaded / e.total);
xhr.send();
选择建议:大部分场景用 fetch;需要上传进度时回退到 XMLHttpRequest。