Learn How to Make Node.js Requests – Best 3 Ways to Make HTTP Request

Last updated on Nov 30,2021 10.2K Views
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...

Learn How to Make Node.js Requests – Best 3 Ways to Make HTTP Request

edureka.co

Node.js is one of the most popular front end frameworks, is heavily used in the industry to create server-based applications. These applications, in turn, helps in serving various data and information to the user. But how exactly does the user relay his requirements to the server? Well, this is done using the HTTP Requests which helps the Node.js developers to ease the entire process. Through the medium of this article on Node.js Requests, I will give you a complete walkthrough of Node.js requests and how to around them.

Below are the topics which I will be covering in this article:

Let’s start off with the very first topic of this article and understand what are Node.js Requests.

What is HTTP Request in Node?

In Node.js, an HTTP Request is basically a message requested by the client to a server over the HTTP i.e hypertext transfer protocol. You can think it of as a packet of information that is sent between the two computers as a primary set of data. This request is then processed by the server and another packet of information is sent back to the client. This packet contains all the necessary data requested by the client and is known as the response. In this article, we will be mostly focussing on the request part.

So let’s understand an HTTP Request in more granular terms. An HTTP request is the mode of browser for transferring data between a client and a web server. This data can be anything including an API, a website, an image, text, etc.

An HTTP Request is usually made up of the following:

  1. Request Line
  2. Headers [0 or more]
  3. Body of the Request [optional]

There are various modules using which you can make the HTTP Requests and process the server requests in the web server space itself. In this Node.js Requests article, I will be talking about a few of them which are heavily used in the industry.

Making Node.js Requests

Below I have listed down the 3 most popular ways to make an HTTP request:

  1. HTTP Module
  2. Request Module
  3. AXIOS

So, let us dig a little deeper into each of these, starting off with the HTTP Module.

Here, I’ll be making Node.js requests by performing queries to a “fake” API: the JSON Placeholder API for everyone’s convenience.

1. HTTP Module

HTTP Module is the standard and an old school way of making an HTTP request. It is a default module which you just need to plug and get started with it without having to install any explicit dependencies. It is one of the core as well as the key module to networking using Node.js.

Generally, beginners in Node.js tend to use http.get and https.get while trying to request or GET something from the API. The main advantage of this module is, that it is native to the API, thus it reduces the need for installing any 3rd party. This makes the process a little faster. Below I have written a code which requests data using an HTTP module.

const https = require("https");
const url = "https://my-json-server.typicode.com/edurekaDemo/noderequest/db";
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);
});
});

This will give you the requested data in the console. Below I have attached the output of my code.

But as said, every coin has two faces, the http module has its cons as well. The HTTP module of Node.js is a bit verbose and doesn’t support ‘promises’. Thus, it becomes a little unreliable and clumsy to be used for development.

In the next section of this Node.js Requests article, I will be talking about the request module which is nothing but an advanced or modified version of the HTTP module.

2. Request Module

The request module of Node.js is one of the most popular Node.js package in the industry for HTTP requests. This package is more on the user-friendly side as compared to the HTTP module which is why it is considered a safe haven for the community for several years. In other words, it is designed in such a way that it facilitates the HTTP requests in the simplest way possible. It is able to do so as it is just a wrapper around the built-in HTTP package of Node.js. Thus, using request, you can make use of all the functionalities of HTTP but in an easier way.

Below I have written a code which requests data using the request module. But before you make a request using this module, you need to install it in your systems using the following command:

npm i request

Once you have successfully installed the request module, you can proceed with the below-given example.

const request = require("request");
const url = "https://my-json-server.typicode.com/edurekaDemo/noderequest/db";
request.get(url, (error, response, body) => {
let json = JSON.parse(body);
console.log(body);
}); 

This will give you the requested data in the console. Below I have attached the output of my code.

Thus, Request module is the best option if you are looking for an easy to use a library which can handle the HTTP requests effortlessly.

But again, while it makes the request process easier it doesn’t have any support for promises and has a lot of dependencies. This leads us to our third way of making Node.js request i.e using axios package.

3. Axios Module

Axios is a Promise based HTTP client which can work for browser as well as in the Node.js environment. It is because Axios provides a single API for handling XMLHttpRequest and node’s HTTP interface. This package is generally used when one is dealing with a complicated series of events. And since building asynchronous code can be really confusing, Promises has become one of the most prominent solutions to this problem.

Below I have written a code which requests data using the request module. But before you make a request using this module, you need to install it in your systems using the following command:

npm i axios

Once you have successfully installed the request module, you can proceed with the below-given example.

const axios = require("axios");
const url = "https://my-json-server.typicode.com/edurekaDemo/noderequest/db";
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); 

This will give you the requested data in the console. Below I have attached the output of my code.

Now that you know the various ways in which you can generate a Node.js Request, let’s now see what is a request object and it’s various properties.

Node.js Request Object

The Request object in Node.js helps in retrieving the values that the client browser has passed to the Node.js server over an HTTP request. It holds the information from the user and assesses in creating a web page dynamically. Based on user inputs it is also capable of performing various server-side operations. You can say,  the request object is used to retrieve information about the current HTTP request such as URL, request header, and data, etc. Below I have listed down the most frequently used properties of the request object.

PropertyDescription
req.appThis helps in holding a reference to the current instance of the express application using the middleware
req.baseUrlThis is used for the URL path on which a router instance was mounted
req.bodyThis help in holding key-value pairs of data submitted in the request body by the client.
req.paramsThis is used for an object holding the properties that are mapped with the route labeled as “parameters”
req.pathThis is used for holding the path of the request URL
req.protocolThis is used for a request protocol string like “http” or “https” when it is requested with TLS
req.secureThis is just a Boolean which returns true if a TLS connection is successfully established

 

With this, I would like to conclude this article on Node.js Requests. I tried my best to keep the content crisp and clear for your ease of understanding. If this has perked up your interest in knowing more about Node.js, you can refer to my other articles on Node.js as well.

If you found this “Node.js Requests” relevant, check out the Node.js Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

Got a question for us? Please mention it in the comments section of this Node.js Requests and we will get back to you.

Upcoming Batches For Node.js Certification Training Course
Course NameDateDetails
Node.js Certification Training Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework