Enjoy 20% off all plans by following us on social media. Check out other promotions!
测验题

How do you make an HTTP request using the Fetch API?

Topics
JAVASCRIPT网络
在GitHub上编辑

TL;DR

To make an HTTP request using the Fetch API, you can use the fetch function, which returns a promise. You can handle the response using .then() and .catch() for error handling. Here's a basic example of a GET request:

fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));

For a POST request, you can pass an options object as the second argument to fetch:

fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));

Making an HTTP request using the Fetch API

Basic GET request

To make a basic GET request, you can use the fetch function with the URL of the resource you want to fetch. The fetch function returns a promise that resolves to the Response object representing the response to the request.

fetch('https://api.example.com/data')
.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));

Handling different response types

The Response object has several methods to handle different types of responses, such as .json(), .text(), .blob(), and .arrayBuffer().

fetch('https://api.example.com/data')
.then((response) => response.text())
.then((text) => console.log(text))
.catch((error) => console.error('Error:', error));

Making a POST request

To make a POST request, you need to pass an options object as the second argument to fetch. This object can include the HTTP method, headers, and body of the request.

fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
})
.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));

Handling errors

Error handling in the Fetch API can be done using the .catch() method. It's also a good practice to check the response.ok property to ensure the request was successful.

fetch('https://api.example.com/data')
.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));

Using async/await

You can also use the Fetch API with async/await for a more synchronous-looking code.

async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
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();

Further reading

在GitHub上编辑