上一篇
fetch api 中文
- 行业动态
- 2025-05-02
- 1
Fetch API是浏览器异步请求接口,替代XMLHttpRequest,支持Promise处理网络请求
Fetch API 详解
基础概念
Fetch API 是浏览器提供的原生接口,用于执行网络请求并处理响应,它基于 Promise 设计,语法简洁且支持异步操作,逐步取代传统的 XMLHttpRequest
。
基本用法
// 发起 GET 请求 fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('网络响应异常'); } return response.json(); // 解析为 JSON }) .then(data => { console.log(data); // 处理数据 }) .catch(error => { console.error('请求失败:', error); });
与 XMLHttpRequest 对比
特性 | Fetch API | XMLHttpRequest |
---|---|---|
语法复杂度 | 简洁(返回 Promise) | 繁琐(需手动监听事件) |
浏览器支持 | 现代浏览器均支持 | 老旧浏览器需 polyfill |
自动处理 CSRF Token | 支持(通过 credentials 选项) | 需手动设置 |
流式处理 | 不支持(需配合 ReadableStream) | 支持(onprogress) |
可中断请求 | 需配合 AbortController | 直接调用 abort() |
常见应用场景
获取 JSON 数据
fetch('https://api.example.com/users') .then(response => response.json()) .then(users => console.log(users));
提交表单数据(POST)
const formData = new FormData(document.querySelector('form')); fetch('/submit', { method: 'POST', body: formData, headers: { 'Content-Type': 'multipart/form-data' // 需手动设置边界类型 } });
下载文件
fetch('https://example.com/file.pdf') .then(response => response.blob()) .then(blob => { const url = URL.createObjectURL(blob); document.getElementById('downloadLink').href = url; });
错误处理
- HTTP 错误状态码:需手动检查
response.ok
或response.status
。 - 网络错误:通过
.catch()
捕获(如断网、DNS 解析失败)。 - 超时控制:需结合
AbortController
实现(Fetch 本身无超时参数)。
高级用法
功能 | 实现方式 |
---|---|
自定义请求头 | headers: {'Authorization': 'Bearer token'} |
处理文本响应 | response.text() |
取消请求 | const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort(); |
跨域请求 | 依赖服务器设置 Access-Control-Allow-Origin |
兼容性处理
- 低版本浏览器:可引入 polyfill(如
whatwg-fetch
)。 - Node.js:需安装
node-fetch
包(npm install node-fetch
)。
相关问题与解答
问题1:如何为 Fetch 请求设置超时时间?
解答:
Fetch API 本身不支持超时参数,但可通过 AbortController
实现:
const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒后终止 fetch('https://api.example.com/data', { signal: controller.signal }) .then(response => response.json()) .then(data => { clearTimeout(timeoutId); // 清除超时 console.log(data); }) .catch(error => { if (error.name === 'AbortError') { console.log('请求超时'); } else { console.error(error); } });
问题2:如何用 Fetch 下载图片并显示在页面上?
解答:
fetch('https://example.com/image.jpg') .then(response => response.blob()) .then(blob => { const imgUrl = URL.createObjectURL(blob); document.getElementById('image').src = imgUrl; // 假设页面有 <img id="image"> }) .catch(error => console.error('图片加载失败