Fetch API 使用
介绍
在现代 Web 开发中,前端与后端的数据交互是必不可少的。Fetch API 是 JavaScript 提供的一种用于发起网络请求的接口,它比传统的 XMLHttpRequest
更简洁、更强大。通过 Fetch API,我们可以轻松地从服务器获取数据、提交表单、更新资源等。
Fetch API 基于 Promise,因此可以更好地处理异步操作。它的语法简单直观,适合初学者快速上手。
基本用法
Fetch API 的核心方法是 fetch()
,它接受两个参数:
- 资源路径(URL):指定要请求的资源地址。
- 配置对象(可选):用于设置请求方法、请求头、请求体等。
以下是一个简单的 GET 请求示例:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
代码解析
fetch('https://jsonplaceholder.typicode.com/posts')
:发起一个 GET 请求,获取帖子列表。.then(response => response.json())
:将响应解析为 JSON 格式。.then(data => console.log(data))
:打印解析后的数据。.catch(error => console.error('Error:', error))
:捕获并处理错误。
response.json()
是 Fetch API 中常用的方法,用于将响应体解析为 JSON 格式。如果需要其他格式,可以使用 response.text()
或 response.blob()
。
请求方法
Fetch API 支持多种 HTTP 请求方法,包括 GET、POST、PUT、DELETE 等。以下是一些常见方法的示例:
1. GET 请求
GET 请求用于从服务器获取数据。
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2. POST 请求
POST 请求用于向服务器提交数据。
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Post',
body: 'This is a new post.',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
3. PUT 请求
PUT 请求用于更新服务器上的资源。
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
title: 'Updated Post',
body: 'This post has been updated.',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
4. DELETE 请求
DELETE 请求用于删除服务器上的资源。
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE'
})
.then(response => {
if (response.ok) {
console.log('Post deleted successfully');
}
})
.catch(error => console.error('Error:', error));
DELETE 请求通常不需要请求体,但某些 API 可能需要额外的配置,请根据实际情况调整。
处理响应
Fetch API 的响应对象包含许多有用的属性和方法,例如:
response.ok
:布尔值,表示请求是否成功(状态码为 2xx)。response.status
:HTTP 状态码。response.headers
:响应头信息。
以下是一个检查响应状态的示例:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.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('Error:', error));
实际应用场景
场景 1:获取用户数据
假设我们需要从服务器获取用户数据并显示在页面上:
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {
const userList = document.getElementById('user-list');
users.forEach(user => {
const li = document.createElement('li');
li.textContent = user.name;
userList.appendChild(li);
});
})
.catch(error => console.error('Error:', error));
场景 2:提交表单数据
假设我们需要提交一个表单并将数据发送到服务器:
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(event.target);
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
});
总结
Fetch API 是 JavaScript 中用于网络请求的强大工具。通过它,我们可以轻松地与后端服务进行数据交互。本文介绍了 Fetch API 的基本用法、常见请求方法以及实际应用场景。希望这些内容能帮助你更好地理解和使用 Fetch API。
附加资源与练习
资源
- MDN Web Docs: Fetch API
- JSONPlaceholder:一个免费的在线 REST API,适合练习 Fetch API。
练习
- 使用 Fetch API 获取 JSONPlaceholder 上的所有帖子,并将标题显示在页面上。
- 创建一个表单,使用 Fetch API 将表单数据提交到 JSONPlaceholder 的
/posts
端点。 - 尝试使用 Fetch API 实现一个简单的 CRUD 操作(创建、读取、更新、删除)。
祝你学习愉快!