5 ways to make HTTP requests in Nodejs

Why it is important and what are the ways to make the HTTP requests in Nodejs? Let’s get clear it up with the below blog.

Here we go . . .

HTTP requests are the process of fetching data from a remote source. It may be a website, an API. In simple, when you are in need of some code to get useful data from any of the remote sources. These HTTP requests emerge as the core part of the modern languages

This request is then processed by the server and another set or pack of information is sent back to the client as the information. This packet(set of information) contains all the necessary data requested by the client and is known as the response.

In our previous blog, we have seen about creating a Nodejs web server to handle HTTP requests.

This blog gives you the solution: several ways to make HTTP requests from your Nodejs applications. 

You may ask us why should we want to make HTTP requests in between. Following the question, there were the two applications coming into play – web scraping and proxying. 

Scrapers – software that downloads web pages, extract data and other related formations from them. 

Proxy – a server act as median or an intermediary, that does forwarding client requests to other servers and returning the responses.

An HTTP request is made up of the following elements:

  • Request Line
  • Headers
  • Body of the Request

An HTTP client sends a request to a server in the form of message in the following format:

  • A Request-line
  • Zero or more header
  • An empty line 
  • Optionally a message-body

Before proceeding to the next step, make sure that you have installed the latest version of Nodejs and NPM.

5 ways to make HTTP requests in Nodejs

REQUEST

Request is a clarified HTTP client that is much user-friendly. When compared to the default HTTP module developers finds Request as more effective. It is very popular among the developer community and is considered a go-to HTTP client for Nodejs projects.

Unlike the HTTP module, this demands you to install this as a dependency from module resources called Node Package Manager (npm) using the following command:

$ npm install request --save

Following is an example code snippet that utilizes Request HTTP client to call a duplicate REST API:

const request = require('request');

request('https://jsonplaceholder.typicode.com/todos/1', { json: true }, (err, res, body) => {

  if (err) { 

      return console.log(err); 

  }

  console.log(body.id);

  console.log(body.title);

});

GOT

Got is another user-friendly like Request. A lightweight HTTP request library for Nodejs. To install Got from Node package manager with the following command:

$ npm install got --save

Just like Axios and Needle, Got will also support Promises. The following code snippet will call duplicate REST API to get todo information:

const got = require('got');

got('https://jsonplaceholder.typicode.com/todos/1', { json: true })

    .then(res => {

      console.log(res.body.id);

      console.log(res.body.title);

    }).catch(err => {

      console.log(err.response.body);

    });

NEEDLE

A good streamable HTTP client for Nodejs which supports proxy, iconv, cookie, deflate and multi-part requests. To install Needle client from Node package manager, initiate the following command in your terminal:

$ npm install needle --save

The following code snippet will do the same task of calling duplicate REST API and printing the details:

const needle = require('needle');

needle.get('https://jsonplaceholder.typicode.com/todos/1', {json: true}, (err, res) => {

    if (err) { 

          return console.log(err); 

      }

    let todo = res.body;

    console.log(todo.id);

    console.log(todo.title);

});

AXIOS

Axios is a Promise based HTTP client for the Nodejs. Unlike the other HTTP clients such as Request and Needle, Axios automatically converts the response data into a JSON object. It is simple, yet a neat way to make an HTTP request in Nodejs. Run the following command in your terminal from the root directory:

$ npm install axios --save

Since it supports Promises, it reduces the need to code to call duplicate REST API as above for HTTP client:

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/todos/1')

  .then(res => {

    console.log(res.data.id);

    console.log(res.data.title);

  })

  .catch(err => {

    console.log(err);

  });

Another benefit of Axios, it supports multiple concurrent requests with axios.all. With a simple illustration we can concurrently call duplicate REST API to get two todos information at once:

const axios = require('axios');

axios.all([

      axios.get('https://jsonplaceholder.typicode.com/todos/1'),

      axios.get('https://jsonplaceholder.typicode.com/todos/2')

    ]).then(axios.spread((res1, res2) => {

      console.log(res1.data.title);

      console.log(res2.data.title);

    })).catch(err => {

      console.log(err);

    });

THE r2 MODULE

The r2 module comes first to use Promises. It is an implementation of the browser’s Fetch API client in Nodejs. Mostly uses the same API as window.fetch with fewer dependencies, That means r2 depends on node-fetch.

 Run the following command in a terminal to execute:

npm i r2

Same as before, the following code snippet will call duplicate REST API to get todo information:

const r2 = require("r2");

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

const getData = async url => {

 try {

   const response = await r2(url).json;

   console.log(response);

 } catch (error) {

   console.log(error);

 }

};

getData(url);

CONCLUSION

Still, Nodejs has various other methods to make HTTP requests that we didn’t list here. With this Nodejs proves its potential in the technical aspects in turn in web application development.

If you’re planning to build a Nodejs web application, Contact us for cost-effective development services.

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn