JavaScript Fetch API
什么是 Fetch API?
Fetch API 是现代浏览器提供的一个用于发起网络请求的接口,它是 XMLHttpRequest 的更强大、更灵活的替代品。Fetch API 使用 Promise,这使得处理异步操作更加简洁和直观。
它提供了一种简单、标准化的方式来跨网络异步获取资源,是现代网页应用程序中进行 AJAX 请求的首选方法。
备注
Fetch API 是 HTML5 的一部分,在大多数现代浏览器中得到支持,但在 Internet Explorer 中不可用。
Fetch API 基础
基本语法
fetch()
方法最简单的形式只需要一个参数 - 要获取资源的 URL:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
这个简单示例展示了 Fetch API 的基本用法:
- 调用
fetch()
并传入 URL - 处理响应(将其转换为 JSON)
- 处理数据
- 捕获并处理可能的错误
Fetch 返回 Promise
fetch()
方法返回一个 Promise,表示获取响应的操作完成(或失败)。
const fetchPromise = fetch('https://api.example.com/data');
console.log(fetchPromise); // 输出: Promise {<pending>}
fetchPromise
.then(response => {
console.log('收到响应!');
return response.json();
})
.then(data => {
console.log('数据已转换为JSON!');
console.log(data);
});
处理响应
当 fetch 请求完成时,返回的 Promise 会解析为 Response 对象,该对象包含了响应的各种信息。
响应数据格式
Response 对象提供了多种方法来处理不同类型的数据:
response.json()
- 将响应解析为 JSONresponse.text()
- 将响应解析为文本response.blob()
- 将响应解析为 Blob(二进制数据)response.formData()
- 将响应解析为 FormData 对象response.arrayBuffer()
- 将响应解析为 ArrayBuffer
每个方法都返回一个 Promise,解析为相应格式的数据。
// 获取JSON数据
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
// 获取文本数据
fetch('https://example.com/text-file.txt')
.then(response => response.text())
.then(text => console.log(text));
// 获取图像数据
fetch('https://example.com/image.jpg')
.then(response => response.blob())
.then(blob => {
const imageUrl = URL.createObjectURL(blob);
const imageElement = document.createElement('img');
imageElement.src = imageUrl;
document.body.appendChild(imageElement);
});