fetch API 是一种现代的、基于 Promise 的 HTTP 请求方法,它提供了一个更灵活和强大的接口来发起网络请求。相比于传统的 XMLHttpRequest,fetch API 提供了更简洁的语法和更好的错误处理能力。
fetch API 的基本用法
发起 GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // 假设响应体是 JSON 格式
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
发起 POST 请求
fetch('https://api.example.com/data', {
method: 'POST', // 或 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'value'
}),
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // 假设响应体是 JSON 格式
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
fetch API 的主要特性
1. Promise 基础
fetch API 返回一个 Promise,允许使用 .then() 和 .catch() 方法来处理异步操作。
2. 请求配置
fetch 接受第二个参数作为配置对象,可以指定请求方法(如 GET, POST)、请求头(headers)、请求体(body)等。
3. 响应处理
fetch 返回的响应对象提供了多种方法来处理响应数据,如 json(), text(), blob() 等。
4. 错误处理
fetch 本身仅在网络请求失败时抛出错误,对于非 2xx 的 HTTP 响应码不会抛出错误。因此,通常需要手动检查响应状态。
常用的 fetch API 方法
fetch(url[, init])
- url: 请求的 URL 地址。
- init: (可选)请求的初始化配置对象。
Response 对象
- Response.ok: 布尔值,表示 HTTP 状态码是否在 200-299 范围内。
- Response.status: HTTP 状态码。
- Response.statusText: HTTP 状态文本。
- Response.headers: 获取响应头。
- Response.arrayBuffer() : 读取响应体作为 ArrayBuffer。
- Response.blob() : 读取响应体作为 Blob。
- Response.formData() : 读取响应体作为 FormData。
- Response.json() : 读取响应体作为 JSON。
- Response.text() : 读取响应体作为字符串。
示例代码
示例 1:获取 JSON 数据
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // 假设响应体是 JSON 格式
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
示例 2:发送 POST 请求
Javascript
深色版本
fetch('https://api.example.com/data', {
method: 'POST', // 或 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'value'
}),
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // 假设响应体是 JSON 格式
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
示例 3:处理不同的响应类型
Javascript
深色版本
fetch('https://api.example.com/image.png')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.blob(); // 假设响应体是图片
})
.then(blob => {
const image = document.createElement('img');
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);
})
.catch(error => {
console.error('Error fetching data:', error);
});
注意事项
-
兼容性:
- 确保你的目标浏览器支持
fetchAPI。如果不支持,可以考虑使用 polyfill(如whatwg-fetch)。
- 确保你的目标浏览器支持
-
超时处理:
fetch本身不支持超时设置,可以通过包装fetch来实现超时机制。
-
取消请求:
- 使用
AbortController可以取消尚未完成的请求。
- 使用
-
错误处理:
- 需要手动检查 HTTP 响应状态,并处理非 2xx 的响应码。
通过以上介绍,你应该能够理解和使用 fetch API 来发起各种类型的 HTTP 请求,并处理响应数据。在实际开发中,fetch API 提供了一种更简洁、更易用的方式来替代传统的 XMLHttpRequest。