The node-fetch Module – Making HTTP Requests in Node.js Using

Making HTTP Requests With Node Fetch Featured Image

In this tutorial, we will be discussing the node-fetch module for Node.js.

When developing a web application, we do not really build everything from scratch. We might want to sometimes “outsource” a few tasks.

For this, we can make use of APIs from other websites that offer services we would like to integrate into our application without having to lift a finger!

In order to achieve such behavior, our application must interact with external web servers to fetch or post data. We can use the in-built window.fetch() when using plain vanilla JavaScript. However, it is very likely you will not use vanilla JavaScript to create web applications.

We, for ton other reasons, will require Node.js. One significant reason to use Node.js is the impeccable level of scalability it offers to applications. Well, coming back to our topic, we cannot use window.fetch() in a Node.js environment. The window object is undefined there.

However, we can use the NPM package, node-fetch. In this guide, we will discuss an example on how to use the node-fetch module. So, let us get started.

What is the node-fetch module?

To start off, let us begin with an introduction to the node-fetch module. The node-fetch module is nothing a lightweight NPM package that makes way to use the fetch() function in Node.js. It also offers a similar functionality window.fetch() to our applications as we find in vanilla JavaScript.

However, there are slight differences tied to it too.

Getting Started with the node-fetch Module in Node.js

Let us now look at an example of creating HTTP requests using node-fetch module in Node.js. We will create a new Node.js application for this project. So, let us start with the steps.

  • Start by creating a Node.js app:
$ npm init -y
Wrote to C:\Users\admin\Desktop\ANEESHA\DEV\JOURNALDEV_TUTS\9_NODE_FETCH_APP\package.json:

{
  "name": "9_node_fetch_app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

You should now see a package.json file created for you with the above-shown default configurations.

  • Create the index.js file:
$ touch index.js
  • 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
  • Let us get started with using the module in our application. let us first import the package in our index.js file:

If you are using Common JS syntax, use:

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 type key as module in the package.json file:
"type": "module"
  • As we learnt earlier, the node-fetch module offers similar functionalities, the syntax is also very much same:
fetch(url[, options]);

The URL parameter simply 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.

The function returns us a Response object that has crucial functions and information of the HTTP request tied to it. The function and are as such:

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 as well as status Text – contain details about the HTTP status code.

ok – equals true if the status code is 2xx (a successful request)

headers – an object containing response headers; the get() function can be used to access a specific header.

Now that we have learned a bit about this module, let us proceed further to actually use it for making HTTP requests.

Sending GET Requests with node-fetch

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

We will use the example used by Stack Abuse –

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

Let us run the file to see if everything’s okay now.

$ node index.js






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

Great! It seems the module is working perfectly fine!

Sending POST Request with node-fetch Module

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’s 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));

Let us now run the file:

$ node 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.

Conclusion

Learn to use the node-fetch package in Node.js to send HTTP requests.

References

https://stackabuse.com/making-http-requests-in-node-js-with-node-fetch/

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