5 Ways to Make HTTP Requests in Node.js
Tags: node, http
Published: 2024-02-20 13:10:25


## Introduction

Learning how to make HTTP requests in Node.js can feel overwhelming as dozens of libraries are 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 make HTTP requests in Node.js, with step-by-step instructions for each method. 

First, we’ll cover HTTP requests and HTTPS requests using the standard library. After that, we’ll show you how to use alternatives like Node Fetch, Axios, and SuperAgent.

## Prerequisites

Before you begin, make sure you have the following:

* [Node.js](https://nodejs.org/en/download/)
* [Node Package Manager (NPM)](https://docs.npmjs.com/cli/v8/commands/npm-install)

## How to Make HTTP Requests in Node.js (5 Methods)

Below, we’ll show you how to make HTTP requests in Node.js via the following five methods:

1. Standard Library (HTTP Module)
2. Standard Library (HTTPS Module)
3. Axios
4. Node Fetch
5. SuperAgent

### 1. Standard Library (HTTP Module)

The standard library in Node.js comes equipped with the default `http` module. It can make an HTTP request without adding bulk with external packages. However, as the module is low-level, it could be more developer-friendly.

Additionally, you would need to use [asynchronous streams](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators) 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.

Typically, you'd use the HTTP Module for testing or demonstration purposes as it is not secure. 

Here's a simple example of making a `GET` request using the `http` module:

```javascript
const http = require('http');

const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  method: 'GET',
};

const req = http.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.end();
```

### 2. Standard Library (HTTPS Module)

If you need to make secure HTTPS requests in Node.js, you can use the `https` module, which is also built into the standard library. The usage is quite similar to the `http` module but with added security. Here's an example:

```javascript
const https = require('https');

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/',
  method: 'GET',
};

const req = https.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.end();
```

### 3. Axios

[Axios](https://github.com/axios/axios) is a popular HTTP client library for Node.js that provides a more user-friendly and feature-rich way to make HTTP requests. Axios simplifies error handling and supports features like automatic JSON parsing and request/response interceptors, making it a great choice for many HTTP request scenarios.

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

```bash
npm install axios
```

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

```javascript
const axios = require('axios');

axios.get('https://example.com')
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });
```

### 4. Node Fetch

[Node Fetch](https://www.npmjs.com/package/node-fetch) is a JavaScript library tailored for Node.js that simplifies making HTTP requests. It offers a straightforward and Promise-based approach for fetching resources from the internet or server, such as GET, POST, PUT, and DELETE requests. Designed for server-side applications, it's compatible with the Fetch API, allowing easy code transition between client-side and server-side environments. 

Additionally, note that [useful extensions](https://github.com/node-fetch/node-fetch) such as redirect limit, response size limit, and [explicit errors for troubleshooting](https://github.com/node-fetch/node-fetch/blob/main/docs/ERROR-HANDLING.md) are available to use with Node Fetch.

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

```bash
npm install node-fetch
```

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

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

fetch('https://example.com')
  .then((response) => response.text())
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error(error);
  });
```

### 5. SuperAgent

[SuperAgent](https://www.npmjs.com/package/superagent) is a lightweight and flexible HTTP client that supports promises and callback-style syntax. It is known for its simplicity and ease of use.

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

```bash
npm install superagent
```

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

```javascript
const request = require('superagent');

request.get('https://example.com')
  .then((response) => {
    console.log(response.text);
  })
  .catch((error) => {
    console.error(error);
  });
```

## 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](https://twitter.com/VonageDev) or the Vonage [Developer Community Slack](https://developer.vonage.com/community/slack).

## Additional Reading

* [3 Ways to Make HTTP Requests in Python (Beginner to Advanced)](https://developer.vonage.com/en/blog/3-ways-to-make-http-calls-with-python-requests-beginner-to-advanced)