How to Use Fetch API in Node JS | Soft Hard System

How to Use Fetch API in Node JS

By Rafid Muhymin Wafi • Published :

Have you ever tried to fetch something in NodeJS and found out that the fetch API doesn't work? If you have experienced this, you are not alone. Fetch is a browser API, and NodeJS doesn't have it. To fetch data in NodeJS, you will have to use the built-in http or the https module.

const https = require("https");

const url = "https://jsonplaceholder.typicode.com/posts";

https

  .get(url, (res) => {
    let response = "";

    res.on("data", (chunk) => {
      response += chunk;
    });

    res.on("end", () => {
      try {
        let json = JSON.parse(body); // do something with JSON
      } catch (error) {
        console.error(error.message);
      }
    });
  })

  .on("error", (error) => {
    console.error(error.message);
  });

If you don't like the verbose syntax of the https module, then don't worry. Some great devs have made the node-fetch npm package for you.

node-fetch

The node-fetch package is a lightweight module that brings the power of the fetch API in NodeJS. To install it, run-


# yarn

yarn add node-fetch

# npm

npm i node-fetch

Then you can import it in a Node JS file and use it as you usually do.

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

const url = "https://jsonplaceholder.typicode.com/posts";

const response = await fetch(url);

const json = await response.json();

The node-fetch package is a replication of fetch for Node JS. So, it includes all the methods and also supports the options object. For example-

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

const url = "https://jsonplaceholder.typicode.com/posts";

const options = {
  method: "Get",
};

const response = await fetch(url, options);

const json = await response.json();

Conclusion

Though Node JS includes two powerful built-in modules for data fetching, their syntax is over-complicated. And for the dev who love the simple syntax of the fetch API, some awesome people have come up with the node-fetch package. It's not only easy to use but also a fast and lightweight solution.

Published : Last Updated : Categorized as : System Tagged as : fetch , nodejs
Rafid Muhymin Wafi | Soft Hard System

Rafid Muhymin Wafi

Hi, I am a 17-year-old boy who is more a web dev than a high school student. I love to play with JavaScript APIs in my free time. Experienced with HTML, CSS, JS, SCSS, NodeJS, React JS, Gatsby JS, Astro JS. Familiar with Next JS and Lit. I also consider myself as a part and contributor to the great Astro JS community. I am also planning to be a full-time blogger at softhardsystem.com

Leave a comment

Loading Comments...