How to Make HTTP Requests in Node.js

Making HTTP requests to external APIs is a fundamental task in backend development. This article guides you through the most popular and efficient ways to perform HTTP requests within a Node.js application. You will learn how to connect your application to external services using the modern built-in fetch API, the widely used Axios library, and the native https module.

1. Using the Built-in Fetch API (Node.js 18+)

Starting from Node.js 18, the global fetch API is available by default. This is the most straightforward method because it requires no external dependencies and uses the same syntax as the browser-based Fetch API.

async function getExternalData() {
  const url = 'https://jsonplaceholder.typicode.com/posts/1';
  
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error.message);
  }
}

getExternalData();

2. Using the Axios Library

Axios is a popular, promise-based HTTP client for Node.js. It automatically transforms JSON data, features robust error handling, and supports request/response interceptors.

First, install the package:

npm install axios

Then, use it in your application:

const axios = require('axios');

async function getExternalData() {
  const url = 'https://jsonplaceholder.typicode.com/posts/1';

  try {
    const response = await axios.get(url);
    console.log(response.data);
  } catch (error) {
    console.error('Error with Axios request:', error.message);
  }
}

getExternalData();

3. Using the Native HTTPS Module

If you are working on an older Node.js version (prior to version 18) and cannot install third-party packages, you can use the built-in https module. This method is more verbose because you must handle the data streams manually.

const https = require('https');

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

https.get(url, (response) => {
  let data = '';

  // Consuming the data stream
  response.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received
  response.on('end', () => {
    try {
      const parsedData = JSON.parse(data);
      console.log(parsedData);
    } catch (error) {
      console.error('Error parsing JSON:', error.message);
    }
  });

}).on('error', (error) => {
  console.error('Error with HTTPS request:', error.message);
});