Making HTTP Requests in Node.js Using Fetch API

The Fetch API is a modern browser API that allows JavaScript to make asynchronous HTTP requests. It offers a flexible and powerful alternative to the older XMLHttpRequest (XHR) object.

With the Fetch API, you can initiate and handle network requests in a straightforward and consistent manner. It is based on Promises, which enable you to manage the results of asynchronous operations through chained .then() and .catch() methods.

Here are some important aspects to know about the Fetch API:

  1. Fetch Function: The core of the Fetch API is the fetch() function. It receives a URL as its input and returns a Promise that resolves to the Response object representing the request’s response.
  2. Promises: The Fetch API relies on Promises, which provide a way to manage asynchronous operations. Promises allow you to chain operations using .then() and handle errors with .catch().
  3. Request and Response Objects: The Fetch API utilizes two primary objects: Request and Response. The Request object represents an HTTP request, while the Response object represents the received response.
  4. HTTP Methods: The Fetch API supports a variety of HTTP methods, such as GET, POST, PUT, DELETE, etc. When making a request, you can specify the desired method through the provided options.
  5. Headers: Custom headers can be set for the request using the Headers object. Headers enable the inclusion of information such as authentication tokens, content types, and more.
  6. Request and Response Body: The Fetch API facilitates the sending and receiving of data in the request and response bodies. Data can be transmitted in different formats, such as JSON, FormData, or plain text.
  7. Error Handling: The Fetch API treats HTTP errors differently compared to the older XHR object. Instead of throwing an error for non-2xx status codes, it considers them successful responses and resolves the Promise. To handle errors, you can examine the response status using the ok property and manage them manually.

The Fetch API is primarily intended for browser environments, however a third-party library like node-fetch is required to replicate the Fetch API’s capabilities in Node.js

node --experimental-fetch your_code.js

To use the Fetch API, you need to follow these steps:

1. Use the `fetch()` function to make a request. Provide the URL of the resource you want to fetch as the first parameter:

   fetch('https://api.example.com/data')
     .then(response => {
       // Handle the response
     })
     .catch(error => {
       // Handle any error that occurred
     });
   

2. Handle the response in the `.then()` method. The `fetch()` function returns a Promise that resolves to the Response object representing the response to the request. You can use various methods available on the Response object, such as `json()`, `text()`, or `blob()`, to extract the data from the response:

fetch('https://api.example.com/data')
     .then(response => response.json()) // Parse response as JSON
     .then(data => {
       // Use the parsed data
     })
     .catch(error => {
       // Handle any error that occurred
     });

3. Optionally, you can check the response status and handle any errors manually. By default, `fetch()` does not reject the Promise for non-2xx status codes. You can verify the response status using the `ok` property or the `status` property:

fetch('https://api.example.com/data')
     .then(response => {
       if (response.ok) {
         return response.json(); // Parse response as JSON
       } else {
         throw new Error('HTTP error: ' + response.status);
       }
     })
     .then(data => {
       // Use the parsed data
     })
     .catch(error => {
       // Handle any error that occurred
     });
   

4. If you need to include headers or specify additional options for the request, you can pass an optional second parameter to the `fetch()` function. This parameter should be an object containing the desired options, such as `method`, `headers`, or `body`:

const options = {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
       'Authorization': 'Bearer your_token'
     },
     body: JSON.stringify({ key: 'value' })
   };

   fetch('https://api.example.com/data', options)
     .then(response => {
       // Handle the response
     })
     .catch(error => {
       // Handle any error that occurred
     });

By following these steps, you can effectively use the Fetch API to make HTTP requests and handle the responses in your JavaScript code.

HTTP headers in Fetch API

When utilizing the Fetch API, you can incorporate headers into your HTTP requests by including an options object as the second parameter in the fetch() function. Within this object, you can define different headers using the headers property. Here’s an example of how to include headers in a Fetch API request:

const options = {
   method: 'GET',
       headers: {
                   'Content-Type': 'application/json',
                   'Authorization': 'Bearer your_token'
         }
};
fetch('https://api.example.com/data', options)
          .then(response => {
                   // Handle the response
          })
           .catch(error => {
                   // Handle any error that occurred
          });

In this example, we’re initiating a GET request to 'https://api.example.com/data' and incorporating two headers: 'Content-Type' and 'Authorization'.

  • 'Content-Type' specifies the format of the data being transmitted in the request body. In this case, we’re indicating that the body content is in JSON format.
  • 'Authorization' is a custom header frequently used for authentication purposes. It generally contains an authentication token, such as a JWT (JSON Web Token), prefixed with a scheme like 'Bearer'.

Sending POST requests

It is also possible for web apps to call an API with a POST method and supply some parameters in the body of the request.

To do this we can set the method and body parameters in the fetch() options.

fetch(url, {
       method: 'post',
       headers: {
                 "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
       },
       body: 'foo=bar&lorem=ipsum'
       })
       .then(json)
       .then(function (data) {
       console.log('Request succeeded with JSON response', data);
       })
       .catch(function (error) {
       console.log('Request failed', error);
       });

Similarly, you can also use the HTTP methods such as DELETE, PUT, etc.

Leave a Comment


Captcha
− 8 = 1


This site uses Akismet to reduce spam. Learn how your comment data is processed.