Fetch API 简介
Fetch API
是现代浏览器中提供的一种新的用于发起网络请求的 API,提供了比 XMLHttpRequest
更强大且灵活的功能。它采用了基于 Promise 的异步操作,可以简化代码结构,提高可读性,特别是在处理异步操作时。
基本用法
下面是一个基本的例子,展示了如何使用 Fetch API 从服务器请求数据并处理响应。
1. 基本 GET 请求
// 使用 Fetch API 发起 GET 请求
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 解析 JSON 格式的响应
})
.then(data => {
console.log(data); // 打印响应的数据
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
2. 说明
fetch(url)
:用于发起请求,url
是请求的资源地址。response.ok
:用于判断响应是否成功(状态码 2xx)。response.json()
:将响应体转换为 JSON 格式的 JavaScript 对象。.then()
:用于处理响应数据或成功回调。.catch()
:用于处理异常情况。
3. POST 请求
使用 Fetch API 发送 POST 请求,可以发送数据到服务器,通常用来提交表单。
// 创建要发送的数据
const postData = {
title: 'foo',
body: 'bar',
userId: 1
};
// 使用 Fetch API 发起 POST 请求
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // 请求方式
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData) // 将 JavaScript 对象转换为 JSON 字符串
})
.then(response => response.json()) // 解析 JSON 格式的响应
.then(data => {
console.log('Success:', data); // 打印成功返回的数据
})
.catch(error => {
console.error('Error:', error); // 错误处理
});
4. 说明
method: 'POST'
:指定请求方式为 POST。headers
:设置请求头,通常 POST 请求需要设置'Content-Type': 'application/json'
,表示发送的是 JSON 格式的数据。body: JSON.stringify(postData)
:将 JavaScript 对象转换为 JSON 字符串并作为请求体发送。
5. 异常处理
使用 Fetch API 进行请求时,可能会出现网络错误或其他问题。因此,建议使用 .catch()
方法来捕获和处理异常。
例如,网络无法连接时,或者发生了其他非 2xx 的状态码时,可以在 .catch()
方法中进行处理。
6. 使用 async/await(简化异步处理)
async/await
可以让你写出更直观、简洁的代码,它是基于 Promise 的语法糖。以下是使用 async/await
改写上述例子的方式:
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data); // 打印数据
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
}
// 调用函数
fetchData();
说明:
async
:声明一个异步函数。await
:用于等待fetch()
返回的 Promise 解析完成。try/catch
:用于捕获和处理异常,使代码更简洁。
7. Fetch API 常见配置选项
Fetch API
的请求配置对象接受多个可选配置项,常见的配置项包括:
- method:HTTP 请求方法,如
'GET'
,'POST'
,'PUT'
,'DELETE'
等。 - headers:请求头,可以设置请求的 Content-Type 或其他头部信息。
- body:请求体,通常用于 POST 或 PUT 请求,包含要发送的数据。
- mode:指定跨域请求的方式,如
'cors'
,'no-cors'
,'same-origin'
等。 - credentials:指定是否发送凭证(如 cookies),可以是
'same-origin'
,'include'
,'omit'
。
8. 使用 Fetch API 处理 JSONP 或跨域请求
如果你需要进行跨域请求,Fetch API
默认会受到同源策略的限制。为了跨域请求,可以设置 CORS(Cross-Origin Resource Sharing) 或在请求中添加特定的头信息。
例如:
fetch('https://example.com/data', {
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
9. 总结
- Fetch API 是一个现代的用于发送 HTTP 请求的 API,替代了传统的
XMLHttpRequest
。 - 它基于 Promise,使得异步请求更加简洁、易于理解。
- 可以方便地发送
GET
、POST
等请求,并支持处理 JSON 格式的数据。 - 配合
async/await
,可以进一步简化异步代码的书写。
通过 Fetch API,你可以轻松实现现代 Web 应用中的数据交互,处理服务器响应,更新页面内容。
发表回复