The Fetch API is a modern interface for making HTTP requests in web browsers and Node.js environments. With the release of Node.js version 18, the Fetch API has become a built-in feature, eliminating the need for external modules like node-fetch when working in Node.js. This topic will explore how to use the built-in Fetch API in Node.js to perform HTTP requests, handle responses, and manage asynchronous code effectively.
What is the fetch API?
The Fetch API provides a more robust and flexible feature set for making HTTP requests compared to the older XMLHttpRequest. It is designed to be promise-based, allowing for more readable and manageable asynchronous code. In Node.js version 18 and later, the Fetch API is available by default, so you can start using it without any additional installation steps.
Making a fetch request
Using the Fetch API in Node.js is straightforward. Here's an example of making a simple GET request:
async function getWeather() {
const response = await fetch('https://api.weather.gov/');
const data = await response.json();
console.log(data);
}
getWeather();In the example above, you define an asynchronous function getWeather that fetches data from an external API. The function uses the built-in fetch function to make an HTTP GET request, waits for the response, parses it as JSON, and then logs it to the console. This is a simple example of how to get and manage data from a web service in a Node.js application.
Handling responses and errors
Properly handling responses and errors is crucial when working with the Fetch API. Here's how you can handle different response statuses and network errors:
async function getUser(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Could not fetch user:', error);
}
}
getUser(1);This code snippet includes error handling to deal with network issues or non-200 status codes. The if (!response.ok) { ... }: Checks whether the HTTP response is successful. The ok property of the response object is a boolean value that indicates whether the response was successful (status code in the range 200-299) or not. If response.ok is false, it means that the request was not successful. In this case, an Error is thrown with a message indicating the HTTP error status. Other available properties and methods of the Response object include:
response.status: This property returns the HTTP status code of the response (e.g., 200 for OK, 404 for Not Found).response.statusText: This property returns the status message corresponding to the HTTP status code (e.g., "OK" for status code 200, "Not Found" for status code 404).response.json(): This method parses the response body as JSON and returns a promise that resolves with the result.
Error handling is implemented within an asynchronous function, getUser which attempts to fetch user data from an API. This approach ensures that the program gracefully handles errors without crashing and provides informative feedback regarding the failure.
Post requests with the fetch API
The Fetch API also allows you to make POST requests and send data to a server:
async function createUser(userData) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
});
const data = await response.json();
console.log('Created User:', data);
}
const newUser = {
name: 'Jane Doe',
email: '[email protected]',
};
createUser(newUser);In the example above, the createUser function sends a POST request with the user data as JSON, demonstrating how to create a new user on the server and log the response.
Performing delete requests
The Fetch API is not only capable of handling GET and POST requests but also allows you to perform DELETE requests. This is useful when you need to remove a resource from the server. Here's an example of how to use the Fetch API to make a DELETE request in Node.js:
async function deleteUser(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log(`User with ID ${userId} has been deleted.`);
} catch (error) {
console.error('Could not delete user:', error);
}
}
deleteUser(1);In this code snippet, the deleteUser function attempts to delete a user by making an HTTP DELETE request to the server. It includes the necessary error handling to manage non-200 status codes and network issues. The function logs a confirmation message upon successful deletion or an error message if the deletion fails.
Using the Fetch API to perform DELETE requests follows a similar pattern to other types of requests, with the primary difference being the method property set to 'DELETE'. This indicates to the server that the request intends to remove the specified resource.
Working with headers and custom requests
Custom headers and request configurations can be necessary for various scenarios, such as authentication:
async function getSecretData(token) {
const response = await fetch('https://api.example.com/secret-data', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
const data = await response.json();
console.log(data);
}
getSecretData('your-token-here');In the code snippet, an asynchronous function getSecretData uses the fetch function to make an HTTP GET request to a specific endpoint (`https://api.example.com/secret-data`). The function takes one parameter, token, to set an 'Authorization' header in the request. This header contains a bearer token, commonly used for access authentication. When you run the fetch call, it returns a promise that, when resolved, gives the response from the server. You then wait for the promise to resolve with the await keyword before getting the JSON body from the response using response.json(). Finally, you print the data to the console. This method is typical for getting to resources that need authentication.
Conclusion
The Fetch API in Node.js is a versatile tool that simplifies making HTTP requests and handling asynchronous operations. With Node.js version 18 and later, you can immediately use the built-in Fetch API without relying on external modules. By following the examples provided, you can utilize the Fetch API in your Node.js applications for both simple data retrieval and more complex requests with fetch API's promise-based architecture. As you become more familiar with its features, you'll find the Fetch API to be an indispensable tool for developing data-driven applications.