返回
掌握 fetch 的精髓:探索指定请求方法和请求体
前端
2023-09-12 16:35:04
浏览器中的 JS - 通过 fetch 学习指定请求方法和请求体
在前端开发中,fetch() 方法是与服务器进行交互获取或发送数据的重要手段。它提供了对 HTTP 请求的强大而灵活的控制,包括指定请求方法和请求体。
请求方法
HTTP 协议提供了多种请求方法,用于执行不同的操作。fetch() 方法支持以下最常用的方法:
- GET: 从服务器检索资源。
- POST: 创建或更新资源。
- PUT: 替换现有资源。
- DELETE: 删除资源。
要指定请求方法,请将其作为 fetch() 方法的第一个参数传递。例如:
fetch('https://example.com/api/users', {
method: 'GET',
});
请求体
请求体是发送到服务器的数据。它通常用于 POST、PUT 和 PATCH 请求。可以使用 JavaScript 内置的 JSON.stringify()
函数将数据序列化为 JSON 格式。
const data = {
name: 'John Doe',
email: 'johndoe@example.com',
};
fetch('https://example.com/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
发送和接收 JSON 数据
JSON(JavaScript 对象表示法)是一种广泛用于网络应用程序的数据格式。fetch() 方法允许轻松发送和接收 JSON 数据。
要发送 JSON 数据,请将 Content-Type
标头设置为 application/json
,并使用 JSON.stringify()
序列化数据。
fetch('https://example.com/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
要接收 JSON 数据,请使用 response.json()
方法。它返回一个 Promise,该 Promise 在数据可用时解析为 JSON 对象。
fetch('https://example.com/api/users')
.then(response => response.json())
.then(data => console.log(data));
示例:使用 fetch 创建用户
让我们来看一个使用 fetch() 方法创建用户的示例:
const data = {
name: 'John Doe',
email: 'johndoe@example.com',
};
fetch('https://example.com/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log('User created:', data))
.catch(error => console.error('Error:', error));
结论
fetch() 方法为浏览器中的 JavaScript 提供了强大的功能,用于与服务器进行交互。通过指定请求方法和请求体,我们可以执行广泛的操作,例如检索数据、创建资源和修改现有数据。通过利用 fetch() 的能力,我们可以创建交互式且高效的 Web 应用程序。