DEV Community

loading...
Cover image for 5 Ways To Make HTTP Requests In Node.js – 2020 Edition
Vonage

5 Ways To Make HTTP Requests In Node.js – 2020 Edition

Nahrin Jalal
Passionate about building inclusive communities and creating technical content that is accessible to all skill levels.
Originally published at nexmo.com on ・4 min read

Learning how to make HTTP requests can feel overwhelming as there are dozens of libraries available, with each solution claiming to be more efficient than the last. Some libraries offer cross-platform support, while others focus on bundle size or developer experience. In this post, we’ll explore five of the most popular ways to achieve this core functionality in Node.js.

The code demonstrations will use the Lord of the Rings themed API, one API to rule them all, for all interactions—simply because I accidentally binge-watched the entirety of this excellent series last weekend.

Lord of the Rings gif

Prerequisites

Ensure you have npm and Node.js installed on your machine, and you’re good to go!

Prefer to jump ahead? This post will cover:

HTTP (The Standard Library)

The standard library comes equipped with the default http module. This module can be used to make an HTTP request without needing to add bulk with external packages. However, as the module is low-level, it isn’t the most developer-friendly. Additionally, you would need to use asynchronous streams for chunking data as the async/await feature for HTTP requests can’t be used with this library. The response data would then need to be parsed manually.

The following code demonstrates how to use the standard http library to make a GET request to retrieve names of books in the Lord of the Rings series:

const https = require('https');

https.get('https://the-one-api.dev/v2/book?api_key=MY_KEY', (resp) => {
  let data = '';

  // a data chunk has been received.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // complete response has been received.
  resp.on('end', () => {
    console.log(JSON.parse(data).name);
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});
Enter fullscreen mode Exit fullscreen mode

Super Agent

SuperAgent is a small HTTP request library that may be used to make AJAX requests in Node.js and browsers. The fact that SuperAgent has dozens of plugins available to accomplish things like prevent caching, convert server payloads, or prefix or suffix URLs, is pretty impressive. Alternatively, you could extend functionality by writing your own plugin. SuperAgent also conveniently parses JSON data for you.

The browser-ready, minified version of SuperAgent is only 6KB (minified and gzipped) and very popular amongst developers.

Enter the following command in your terminal to install SuperAgent from npm:

npm install superagent --save
Enter fullscreen mode Exit fullscreen mode

The following code snippet showcases how to use SuperAgent to make a request:

const superagent = require('superagent');

(async () => {
  try {
    const queryArguments = {
      api_key: 'MY_KEY'
    }

    const response = await superagent.get('https://the-one-api.dev/v2/book').query(queryArguments)
    console.log(response.body.name);
  } catch (error) {
    console.log(error.response.body);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Axios

Axios is a promise based HTTP client for the browser and Node.js. Like SuperAgent, it conveniently parses JSON responses automatically. What sets it further apart is its capability to make concurrent requests with axios.all—which, for example, would be an efficient way to retrieve quotes from the Lord of the Rings movies and books at the same time.

Enter the following command in your terminal to install Axios from npm:

npm install axios --save
Enter fullscreen mode Exit fullscreen mode

The following code snippet showcases how to use Axios to make a request:

const axios = require('axios');

(async () => {
  try {
    const response = await axios.get('https://the-one-api.dev/v2/book?api_key=MY_KEY')
    console.log(response.data.name);
  } catch (error) {
    console.log(error.response.body);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Node Fetch

Node Fetch is a light-weight module that brings the Fetch API to Node.js. With fetch (in the browser or via Node Fetch) you can mix the .then and await syntax to make converting the readable stream into JSON a bit nicer—so data, as demonstrated in the snippet below, has the JSON without needing an awkward middle variable. Additionally, note that useful extensions such as redirect limit, response size limit, explicit errors for troubleshooting are available to use with Node Fetch.

Enter the following command in your terminal to install Node Fetch from npm:

npm install node-fetch --save
Enter fullscreen mode Exit fullscreen mode

The following code snippet showcases how to use Node Fetch to make a request:

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

(async () => {
  try {

    const data = await fetch('https://the-one-api.dev/v2/book? 
    api_key=MY_KEY').then(r => r.json())

    console.log(data.name);
  } catch (error) {
    console.log(error.response.body);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Got

Got is another intuitive and powerful HTTP request library for Node.js. It was initially created as a light-weight alternative to the popular Request (now deprecated) package. To see how Got compares to other libraries, check out this detailed chart.

Unlike Axios and SuperAgent, Got does not parse JSON by default. Note that { json: true } was added as an argument in the code snippet below to achieve this functionality.

For modern browsers and Deno usage, the folks behind Got produced Ky. Ky is a tiny HTTP client with no dependencies based on the browser Fetch API.

Enter the following command in your terminal to install Got from npm:

npm install got --save
Enter fullscreen mode Exit fullscreen mode

The following code snippet showcases how to use Got to make a request:

const got = require('got');

(async () => {
  try {
    const response = await got('https://the-one-api.dev/v2/book?api_key=MY_KEY', { json: true });
    console.log(response.body.name);
  } catch (error) {
    console.log(error.response.body);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

This post demonstrated how to achieve HTTP request functionality using some of what are currently considered to be the most popular libraries in Node.js.

Other languages also have a myriad of libraries to tackle HTTP requests. What language do you want us to write about next? Let us know! We’d love to hear your thoughts or answer any questions on Twitter or the Vonage Developer Community Slack.

The post 5 Ways To Make HTTP Requests In Node.js – 2020 Edition appeared first on Vonage Developer Blog.

Discussion (0)