Fetch API 详解
Fetch API 是现代 JavaScript 中用于发起网络请求的标准 API,它比传统的 XMLHttpRequest 更强大、更灵活,且基于 Promise 实现。
基本语法
javascript
fetch(resource [, init])
.then(response => {
// 处理响应
})
.catch(error => {
// 处理错误
});
参数说明
-
resource: 请求的资源路径(URL)
-
init (可选): 配置对象,可以包含以下属性:
method
: 请求方法(GET, POST, PUT, DELETE等)headers
: 请求头信息body
: 请求体数据mode
: 请求模式(cors, no-cors, same-origin)credentials
: 是否发送 cookies(include, same-origin, omit)cache
: 缓存模式redirect
: 重定向处理方式referrer
: 引用来源signal
: AbortSignal 用于取消请求
常见请求示例
1. GET 请求
javascript
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('请求失败:', error));
2. POST 请求
javascript
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify({
name: 'John',
age: 30
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
3. 上传文件
javascript
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('https://api.example.com/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(result => console.log('上传成功:', result))
.catch(error => console.error('上传失败:', error));
响应处理
Fetch API 返回的 Response 对象包含以下常用属性和方法:
属性
ok
: 布尔值,表示请求是否成功(状态码 200-299)status
: HTTP 状态码statusText
: 状态文本headers
: 响应头信息url
: 请求的 URL
方法
json()
: 解析响应体为 JSONtext()
: 获取响应体文本blob()
: 获取响应体为 Blob 对象formData()
: 获取响应体为 FormData 对象arrayBuffer()
: 获取响应体为 ArrayBuffer
错误处理
Fetch API 的错误处理需要注意:
- 网络错误(如无法连接)会触发 catch
- HTTP 错误状态(如 404, 500)不会触发 catch,需要检查
response.ok
javascript
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('请求出现问题:', error));
高级用法
1. 设置超时
javascript
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/data', {
signal: controller.signal
})
.then(response => {
clearTimeout(timeoutId);
return response.json();
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('请求超时');
} else {
console.error('其他错误:', error);
}
});
2. 并发请求
javascript
Promise.all([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2')
])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
console.log('数据1:', data[0]);
console.log('数据2:', data[1]);
})
.catch(error => console.error('请求失败:', error));
3. 自定义请求拦截
javascript
// 请求拦截器
const originalFetch = window.fetch;
window.fetch = async (...args) => {
console.log('发起请求:', args[0]);
// 可以在这里添加认证token等
const response = await originalFetch(...args);
console.log('收到响应:', response);
return response;
};
注意事项
- Fetch 默认不会发送或接收 cookies,需要设置
credentials: 'include'
- 错误状态码(如 404, 500)不会触发 catch,需要检查
response.ok
- Fetch 不支持直接监控上传/下载进度(可以使用 XMLHttpRequest 替代)
- 在 Node.js 环境中,需要使用 node-fetch 或类似 polyfill
Fetch API 提供了强大而灵活的网络请求能力,是现代 Web 开发中处理 HTTP 请求的首选方式。