DEV Community

Atta
Atta

Posted on • Edited on • Originally published at attacomsian.com

7 Ways to Make HTTP Requests in Node.js

This post was originally published on attacomsian.com/blog.


HTTP requests are a core part of the most of the modern languages. It can be challenging for new developers to learn how to make HTTP requests to exchange data. Luckily, for Node.js developers, it is not the case. There are many battle-tested solutions available for making any kind of HTTP request. Let's take a look at some of the most popular Node.js libraries that support HTTP requests.

For the testing purpose, we will be using JSONPlaceholder fake todo REST API for all our examples. Our REST API returns the following JSON response:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Before moving forward, make sure you have installed the latest LTS versions of Node.js and npm on your machine.

1. HTTP — Standard HTTP Library

Both HTTP and HTTPS modules are packed in the standard library. With these modules, you can easily make a HTTP request without installing external packages. But, unfortunately, these are low-level modules and are not very user-friendly as compared to other solutions.

const https = require('https');

https.get('https://jsonplaceholder.typicode.com/todos/1', (response) => {
  let todo = '';

  // called when a data chunk is received.
  response.on('data', (chunk) => {
    todo += chunk;
  });

  // called when the complete response is received.
  response.on('end', () => {
    console.log(JSON.parse(todo).title);
  });

}).on("error", (error) => {
  console.log("Error: " + error.message);
});

2. Request

Request is a simplified HTTP client which is much more user-friendly as compared to default HTTP module. It is very popular among the community and is considered a go-to HTTP client for Node.js projects.

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

$ npm install request --save

Following is an example code snippet that uses Request HTTP client to call our fake 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);
});

3. Needle

Needle is a streamable HTTP client for for Node.js which supports proxy, iconv, cookie, deflate and multi-part requests. To install Needle from npm, run the following command in your terminal:

$ npm install needle --save

The following code snippet will do the same task of calling our fake 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);
});

Starting from version 2.0.x, Needle also support Promises. Promises are good to write more complicated code that involves chain of events. The above code snippet can be written using Promises as following:

const needle = require('needle');

needle.get('https://jsonplaceholder.typicode.com/todos/1', {json: true})
    .then(res => {
        let todo = res.body;
        console.log(todo.id);
        console.log(todo.title);
    }).catch(err => {
        console.log(err);
    });

You can also spot the difference in above code snippet that error handling is done with .catch() since we are using Promises now.

4. Axios

Axios is a Promise based HTTP client for the browser and Node.js. Unlike above mentioned HTTP clients, Axios automatically transforms the response data into JSON object. Run the following command in your terminal from your project root directory:

$ npm install axios --save

Since it supports Promises, we need to write much less code to call our fake REST API as we did 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 is that it supports multiple concurrent requests with axios.all. For example, we can concurrently call our fake 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);
    });

5. SuperAgent

SuperAgent is another popular HTTP library similar to Axios used for making AJAX requests in Node.js as well as browsers. Just like Axios, it does the parsing of response data into JSON which is pretty cool. Install SuperAgent with from npm with the following command:

$ npm install superagent --save

Following is a code snippet that uses SuperAgent to call our fake REST API:

const superagent = require('superagent');

superagent.get('https://jsonplaceholder.typicode.com/todos/1')
.end((err, res) => {
  if (err) { 
      return console.log(err); 
  }
  console.log(res.body.id);
  console.log(res.body.title);
});

SuperAgent is highly extendable via plugins. There are dozens of plugins available for SuperAgent to perform different tasks such as no caching, URLs prefixes and suffixes etc. You can easily write your own plugin to extend the functionality of SuperAgent.

6. Got

Got is another user-friendly and lightweight HTTP request library for Node.js. Install Got from npm with the following command:

$ npm install got --save

Just like Axios and Needle, Got supports Promises as well. The following code snippet will call our fake 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);
    });

7. Node-fetch

Node-fetch is a light-weight HTTP request library that brings browser's window.fetch functionality to Node.js. You can install Node-fetch from npm with the following command in your terminal:

$ npm install node-fetch --save

Similar to Axios, Node-fetch latest release supports Promises. Following is the code snippet that calls our fake REST API to obtain todo information using Node-fetch module:

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

fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(res => res.json()) // expecting a json response
    .then(json => {
        console.log(json.id);
        console.log(json.title);
    })
    .catch(err => {
        console.log(err);
    });

Conclusion

This post does not cover all the HTTP request libraries available for Node.js. It only explains how the HTTP functionality works in some of the most popular HTTP clients in Node.js. There are dozens of other HTTP clients available for Node.js such as simple-get which provides a simplest way to make HTTP requests and supports HTTPS, redirects, and streams in less than 100 lines.

What is your favorite HTTP client to make HTTP requests in Node.js? Feel free to tweet me and let me know or ask any further questions.


✌️ I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter to get web development tutorials & protips every week.

Top comments (1)

Collapse
 
ajay4uuak profile image
Ajay

Sir I have seen an article of yours in attacomsian regarding array[string] how to achieve that through mongoose and nodejs waiting for your answer