测验

如何使用 Fetch API 发出 HTTP 请求?

主题
JavaScript网络
在GitHub上编辑

TL;DR

要使用 Fetch API 发出 HTTP 请求,您可以使用 fetch 函数,该函数返回一个 promise。您可以使用 .then().catch() 来处理响应,以进行错误处理。 这是一个 GET 请求的基本示例:

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));

对于 POST 请求,您可以将一个选项对象作为第二个参数传递给 fetch

fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));

使用 Fetch API 发出 HTTP 请求

基本的 GET 请求

要发出基本的 GET 请求,您可以使用 fetch 函数,并使用您要获取的资源的 URL。fetch 函数返回一个 promise,该 promise 解析为表示对请求的响应的 Response 对象。

fetch('https://jsonplaceholder.typicode.com/todos/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));

处理不同的响应类型

Response 对象有几种方法来处理不同类型的响应,例如 .json().text().blob().arrayBuffer()

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.text())
.then((text) => console.log(text))
.catch((error) => console.error('Error:', error));

发出 POST 请求

要发出 POST 请求,您需要将一个选项对象作为第二个参数传递给 fetch。此对象可以包括 HTTP 方法、标头和请求正文。

fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
})
.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));

处理错误

可以使用 .catch() 方法在 Fetch API 中进行错误处理。 检查 response.ok 属性以确保请求成功也是一个好习惯。

fetch('https://jsonplaceholder.tyicode.com/posts/1/comments') // Typo in the URL
.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));

使用 async/await

您还可以将 Fetch API 与 async/await 结合使用,以获得更具同步感知的代码。

async function fetchData() {
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/todos/1',
);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();

延伸阅读

在GitHub上编辑