Making HTTP Requests in Node.js With node-fetch

When developing web applications, we don’t actually build everything from scratch. We may sometimes want to “outsource” certain tasks. For this, we can use APIs from other websites that offer services that we integrate into our application without lifting a finger!

To achieve this, we can use the built-in window.fetch() when using plain vanilla JavaScript. However, in Node.js window object is undefined. So we can use a Node.js third-party module, node-fetch instead.

Making HTTP Fetch Requests With node-fetch

Node.js provides us with NPM containing various modules that can interact with APIs to fetch and manipulate data. One of them is the node-fetch module. 

The node-fetch module method fetch() can be used to perform the HTTP fetch operation. It provides support for the Fetch API, making it easier to make API requests than Axios or any other third-party module.

Syntax:

fetch(url[, options]);

Parameters:

  • The URL parameter contains the direct URL to the resource we want to retrieve. The function will throw an error if it is not an absolute URL.
  • When we want to use fetch() for something other than a simple GET request, we use the optional options parameter.

Return:

The fetch() function returns a promise that resolves to a Response object containing functions and information about the received response:

  • text() – returns the body of the response as a string.
  • json() – converts the response body to a JSON object and returns an error if the body cannot be parsed.
  • status/statusText – contains details about the HTTP status code.
  • ok – equals true if the status code is 2xx (a successful request)
  • headers – an object containing response headers

Alternative to fetch(): Getting Data from a RESTful API

Getting Started with node-fetch Module

To start making HTTP requests using this Node Fetch API, follow the below steps:

Step 1: Start by initializing a Node.js project.

$ npm init -y

If you successfully see a package.json file created with the above-shown default configurations, let’s move on to step 2.

Step 2: Create the index.js file where we will write code for performing requests and response operations.

$ touch index.js

Step 3: Install the node-fetch NPM module:

$ npm i node-fetch

added 5 packages, and audited 6 packages in 6s

2 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Here we have used npm i, instead of npm install to install the module, both are the same. It is just a shorter form.

Step 4: For using the module it is required first to import it in the file we want to use it, in our case it is “index.js”, so let’s import it here.

If you are using Common JS syntax, use the below syntax for importing the package:

const fetch = require('node-fetch');

If you prefer ESM, use this syntax for importing the package:

import fetch from 'node-fetch';

If you are using node-fetch version 3.x.x, then make sure you only use ESM syntax for importing. Also, DO NOT forget to add set a key “type” with the value “module” in the package.json file:

"type": "module"

Sending GET Request With node-fetch

Let us send a simple GET request to Google’s homepage:

fetch('https://google.com')
    .then(res => res.text())
    .then(text => console.log(text));

If you try to run the script using the node index.js command in the old Node version it will throw an error “ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time”, so try using the below command instead.

node --experimental-modules index.js

Output:

$ node --experimental-modules index.js
<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image">

.... OUTPUT CUT OUT FOR THIS ARTICLE ....

Great! It seems the module is working perfectly fine!

Sending POST Request With node-fetch

Let us now send a POST request to send data to an external web server. We will need an additional optional parameter, without which our request is simply a GET request. We will use the method, headers, and body parameters.

Let us send some data to JSONPlaceholder Todos:

let todo = {
    userId: 41,
    title: "read a book",
    completed: false
};

fetch('https://jsonplaceholder.typicode.com/todos', {
    method: 'POST',
    body: JSON.stringify(todo),
    headers: { 'Content-Type': 'application/json' }
}).then(res => res.json())
    .then(json => console.log(json));

Output:

$ node --experimental-modules index.js
{ userId: 41, title: 'read a book', completed: false, id: 201 }

Great! We have now successfully learned to send GET and POST requests using the node-fetch module.

Using Async Await Syntax

With fetch(), we can also use the async/await syntax by creating an async function, as shown below:

async function fetchData() {
    const response = await fetch('https://google.com');
    const text = await response.text();
    console.log(text);
}

fetchData();

This makes our code more readable and asynchronous and also eliminates the need for .then() chaining.

Error Handling

Additionally, we can use try/catch with the async/await block to catch error:

async function fetchData() {
    try {
        const response = await fetch('https://google.com');
        const text = await response.text();
        console.log(text);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

fetchData();

Using try/catch lets us handle any errors that occur during the fetch operation, this helps us manage exceptions and control error responses.

Conclusion

Performing HTTP requests directly from a browser is easy, but when it comes to building a full-fledged server-side application it becomes completely different from client-side fetch.

For server-side Node.js with fetch API gives advanced usage. Implementing Fetch API to Node.js can be done by using multiple third-party modules. One of them, the easier to implement is the node-fetch module. It helps those who want to send get, post, etc requests from the server side.

Reference

https://www.npmjs.com/package/node-fetch

Aneesha S
Aneesha S
Articles: 171