Update appNew update is available. Click here to update.
Last Updated: May 13, 2022

Making HTTP requests with Node.js

Author Rubleen Kaur
0 upvotes

 

Introduction

HyperText Transfer Protocol(HTTP) is used to transmit multimedia documents and enhance the website’s collaborative features. HTTP requests are a means to fetch data from a remote source. The data could be anything from an API, a website, or something else. Every developer should be familiar with how to perform HTTP requests using Node Js. This article will cover you for that. This article covers a few ways on how you can make HTTP requests using Node Js. 





 

A few pre-requisite you need before moving on to the article is 
→ Basic Understanding of Javascript and ES6

→ Node Js (Basics)

 

 

 

So I hope you are now ready to dive in to learn more about the HTTP requests with NodeJs.

 

Now, you’d be wondering why even make these HTTP requests, right?

Let’s read about it now. 

Why make HTTP requests?

The most straightforward answer to your question is that we will interact with different remote API and web servers as a developer. All the data in the world is almost available in API, weather forecast, location services, medicinal data. 

 

Making HTTP requests using http.get and https.get

The developer’s first choice is to use the standard http.get or https.get for making requests in Node.js.

These are used when we need to get something from the API.

Let’s go through a code sample to understand it better:

codingninjas.js

const https = require("https");
const url = "https://jsonplaceholder.typicode.com/posts/1";

https.get(url, res => {
  res.setEncoding("utf8");
  let body "";
  res.on("data", data => {
    body += data;
  });
  res.on("end", () => {
    body JSON.parse(body);
    console.log(body);
  });
});


To run the above code, use the command - 

 

node codingninjas.js

 

OUTPUT

 

Now let’s go through the code and try to understand what is happening. The HTTP.get method expects the first argument as an URL, and the second argument is a callback. The return statement is an HTTP.ClientRequest Object. 

 

Making HTTP requests using the request module

Making HTTP requests using the request module has been a viral NPM module. It supports both https and http, and it follows the redirect by default. 


To run the given code, use the following statement.


 

node codingninjas.js

 

codingninjas.js

const request = require("request");
const url = "https://jsonplaceholder.typicode.com/todos/1";

request.get(url, (errorresponse, body) => {
  let json = JSON.parse(body);
  console.log(json);
});

 

OUTPUT

 

 

Making HTTP requests using the node-fetch module

The fetch library is also a built-in library and is used for making API calls. Fetch relies on the concept of promises. Well, now you would be wondering what promises are, right?

Promises are an object which represents a point in time when an asynchronous task is either completed or is failed. In Promises, the errors in any then statement are caught using the catch statement. 

 

Let’s go through a code to understand better:

 

To run the given code, use the following statement


 

node codingninjas.js

 

codingninjas.js

 

const fetch = require("node-fetch")

const body = {
  title"foo",
  body"bar",
  userId1
}

fetch("https://jsonplaceholder.typicode.com/todos/1", {
  method"post",
  bodyJSON.stringify(body),
  headers: { "Content-Type""application/json" }
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err))

 

Making HTTP requests using the r2 module

The r2 module uses the Promises and is one way to implement the browser's Fetch API. The r2 modules depend on the node-fetch module.


Let’s go through a code to understand better:

 

To run the given code, use the following statement


 

node codingninjas.js

 

codingninjas.js

const r2 = require("r2");
const url"https://jsonplaceholder.typicode.com/todos/1";

const getData = async url => {
  try {
    const response = await r2(url).json;
    console.log(response);
  } catch (error) {
    console.log(error);
  }
};

getData(url);

 


OUTPUT

 

 

Making HTTP requests using the Axios module

 

Axios is one of the best and most famous libraries used for making requests. The library needs to be installed using the node npm keyword. 

 

npm install axios --save

 

Axios provides us with further control over the request, and it simplifies the process of making HTTP requests and error handling. It offers various features like response timeouts and automatic JSON transformation, progress indicators, etc. 

Let’s go through a code to understand better:

 

To run the given code, use the following statement

 

node codingninjas.js

 

codingninjas.js

const axios = require("axios");
const url"https://jsonplaceholder.typicode.com/posts/1";

const getData = async url => {
  try {
    const response = await axios.get(url);
    const data = response.data;
    console.log(data);
  } catch (error) {
    console.log(error);
  }
};

getData(url);

 

OUTPUT

 

Frequently Asked Questions

 

  1. What are HTTP requests in Nodejs?

    Ans:  HTTP requests are a means to fetch data from a remote source. The data could be anything from an API, a website, or something else. Every developer should be familiar with how to perform HTTP requests using Node Js.

     
  2. What are different kinds of HTTP requests?

    Ans: The most frequent types of request methods are GET and POST, but many others, including HEAD, PUT, DELETE, CONNECT, and OPTIONS. 

     
  3. What is the HTTP request method?

    Ans: HTTP defines a set of request methods used to indicate the desired action performed for a given resource. 

     

 

Key Takeaways

 

Hey everyone, so let’s brief out the article. Let’s discuss in brief whatever we have discussed here. 

  •  HTTP requests are a means to fetch data from a remote source. The data could be anything from an API, a website, or something else. Every developer should be familiar with how to perform HTTP requests using Node Js. This article will cover you for that. This article covers a few ways on how you can make HTTP requests using Node Js. 
  • We have further covered a few ways you can perform HTTP requests using different modules provided by NodeJs. 

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

Happy Learning Ninjas!
 

Previous article
Node.js File System
Next article
Uninstalling npm Packages
Codekaze-June23 India's Biggest Tech Hiring Challenge is LIVE!
Register Now
Go on top