Fetch API 完全指南
Fetch API 是现代 JavaScript 中进行网络请求的标准方法,替代了老旧的 XMLHttpRequest。
基本用法
GET 请求
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Async/Await 语法
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
POST 请求
async function postData(data) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
const result = await response.json();
return result;
}
响应处理
检查状态码
async function fetchWithCheck(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
不同数据类型
// JSON
await response.json();
// 文本
await response.text();
// Blob(文件)
await response.blob();
// ArrayBuffer
await response.arrayBuffer();
// 表单数据
await response.formData();
请求头
fetch('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
'Accept': 'application/json',
},
});
Query 参数
const params = new URLSearchParams({
page: 1,
limit: 20,
sort: 'date',
});
fetch(`https://api.example.com/data?${params}`);
错误处理
网络错误
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('Fetch error:', error);
});
超时处理
function fetchWithTimeout(url, options = {}, timeout = 5000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), timeout)
),
]);
}
文件上传
单文件上传
async function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData,
});
return response.json();
}
多文件上传
async function uploadMultipleFiles(files) {
const formData = new FormData();
files.forEach(file => formData.append('files', file));
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData,
});
return response.json();
}
请求选项
const options = {
method: 'GET', // GET, POST, PUT, DELETE, PATCH
headers: {}, // 请求头
body: JSON.stringify(data), // 请求体(GET 不支持)
mode: 'cors', // cors, no-cors, same-origin
credentials: 'include', // include, same-origin, omit
cache: 'default', // default, no-store, reload
redirect: 'follow', // follow, error, manual
referrer: 'no-referrer',
};
取消请求
const controller = new AbortController();
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data', {
signal: controller.signal,
});
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request was aborted');
}
}
}
// 取消请求
controller.abort();
总结
Fetch API 的关键要点:
- 基于 Promise,支持 async/await
- 简洁的语法和强大的功能
- 支持流式数据处理
- 内置 CORS 支持
更多详情请参考 MDN Fetch API