How To Make An HTTP Request in NodeJs? Http Mechanism & Libraries

Pick Javascript and master the art of both front-end and back-end development.

In our Node.js series of articles we have together covered till date:

  1. Getting Started With Node.js : A Beginners Guide
  2. All About Node.Js You Wanted To Know ?
  3. Node. Js Vs PHP: Battle for Supremacy & Survival
  4. NodeJs Vs Ruby On Rails : Analysis Worth Doing !

Where we have understood all the fundamentals of Node.js, we will now get more into the details of what Node.js as a runtime environment has to offer . Today we will try to understand How to make an HTTP request to the Web server in Node.js .

Requirement:

We are assuming you have prior knowledge of making HTTP connection and have installed latest Node.js & npm on your machine.

Node.js gave us many ways to handle http requests some of which are

  1. Using Standard HTTP Library
  2. Using Request Library
  3. Axios HTTP client

etc…

Today we will discuss two of these and will continue with remaining methodology in our next in the series…

A: Using Standard HTTP Library:

There is a default HTTP module in he Node.js library , you don’t have to worry about installing any third party/external dependencies to use it so you can quickly get into plugging it and use it. The only drawback with this module is that it may not be very user friendly to use .

An example Code snippet 1.0 : Using GET :

var http = require('http');
function getLoginDetails(callback) {
return http.get({
        host: 'locatemap.in',
        path: '/userDetail'
    }, function(response) {
        // Continuously update stream with data
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {
// Data received, let us parse it using JSON!
            var parsed = JSON.parse(body);
            callback({
                userDetail: parsed.name,
                userId: parsed.Id
            });
        });
    });
},

This is the simplest example of creating an HTTP request with the native Node. js http module .

B. Using Request Library :

Request is a simplified HTTP client comparable to Python’s requests library. It has been widely used and popular among the developer community. It helps you swiftly go through your task and is extremely user friendly. Only thing is that you need it to be externally installed using npm as shown below:

Go to your local directory where you want your code to live & run and type this command as shown in code snippet 2. using npm :

code snippet 2.0 :

npm install request@2.x.x //Install the latest one.

See the code snippet 3.0 , it requires very less code to be written as compared to conventional HTTP module as shown in code snippet 1.0 :

const request = require(‘request’);
request(‘https://api.locatemap.in/userId/detail?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body.url);
console.log(body.explanation);
});

Also, there is a request-promise library to achieve this we will cover it and others method of http connection request in our upcoming series .

Some Infographics For You :

A Comparison Of AngularJs Vs NodeJs:

Time to leave you all with some infographics regarding JS framework worth reading

Source: Dzone

If you are 💚 💚 my contribution do 👏 👏 clap , Click Here and subscribe to reach out to me for more and I would feel blessed to hear you and respond back.

Disclaimer ! : This Article is originally written for www.techprenuer.com

 

Pramod Chandrayan

Founder & CEO (Mobibit Soft (P) Ltd) | Mobile App Development Consultant | Startup Mentor | Spiritual Seeker

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Related posts

Leave a Comment