fetch
的基本用法fetch
返回一个 Promise,可以用于发起 GET、POST 等各种类型的 HTTP 请求。
// 发起一个 GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
基于 Promise:
fetch
返回一个 Promise,这使得处理异步请求变得更加简洁和直观,能够利用 async
/await
语法。async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();
语法简洁:
XMLHttpRequest
,fetch
的 API 更加简洁和易读。Stream API 支持:
fetch
支持流(Stream),可以逐步处理响应体(如处理大文件)。灵活性高:
默认不发送 cookies:
fetch
不会发送 cookies,需要手动设置 credentials
选项。fetch('https://api.example.com/data', {
credentials: 'include'
});
不自动拒绝 HTTP 错误状态:
fetch
只会在网络故障时或请求被阻止时(如 CORS 错误)才会被拒绝。对于 HTTP 错误状态码(如 404, 500),它不会自动抛出错误,需要手动检查 response.ok
。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));
不支持超时控制:
fetch
没有内置的超时功能,需要手动实现。const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000); // 5秒后超时
fetch('https://api.example.com/data', { signal })
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
if (error.name === 'AbortError') {
console.error('Fetch request timed out');
} else {
console.error('Fetch error:', error);
}
});
CORS 支持有限:
fetch
遵循严格的 CORS(跨域资源共享)策略,有时需要额外的服务器端配置来允许跨域请求。兼容性问题:
fetch
在老版本浏览器(如 IE)中不受支持,需要使用 polyfill(如 whatwg-fetch
)来提供兼容性支持。fetch
提供了一个现代化、简洁和灵活的方式来进行网络请求。尽管它有许多优点,如基于 Promise 的设计和更简洁的 API,但它也有一些不足之处,如不自动拒绝 HTTP 错误状态和缺乏内置的超时控制。理解这些优点和不足,有助于在项目中更好地使用 fetch
,并根据需求进行必要的补充和调整。