Fetch API
Fetch API是现代浏览器提供的原生HTTP客户端,基于Promise,提供更简洁的异步请求方式。
Fetch特性
基于Promise
支持async/await语法,简化异步处理
链式调用
可链接多个.then()处理步骤
标准化
现代Web标准,逐步替代XMLHttpRequest
灵活性
支持各种HTTP方法和请求配置
实现示例
// GET请求
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
}
}
// POST请求
async function postData(data) {
try {
const response = await fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
return await response.json();
} catch (error) {
console.error('Post error:', error);
}
}