How to send HTTP requests in Node.js with node-fetch

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

In this tutorial, we will explore how to use the node-fetch library, a Node.js module that enables you to perform HTTP requests in a way that is highly reminiscent of the native Fetch API available in browsers. This library provides a simple interface for making requests and processing responses, making it an essential tool for backend development and server-side applications that need to communicate with other web servers or APIs.

Before diving into the examples, you need to have Node.js installed on your system. You can verify this by running node -v in your terminal. If you need to install Node.js, visit Node.js official site.

Once you have Node.js setup, you also need to install node-fetch. Create a new project directory, navigate into it, and initialize a new Node.js project with npm init. Then, install node-fetch by running npm install node-fetch.

Basic Usage

First, let’s cover the simplest way to send an HTTP GET request to retrieve data from a server. We’ll request JSON data from a placeholder API:

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

async function getTodos() {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const data = await response.json();
  console.log(data);
}

getTodos();

This function fetches data and logs it to the console when the promise resolves. Make sure to handle errors properly using try-catch blocks in production code.

Handling Responses

It is important to properly handle HTTP responses when they are received. The following example shows how to check for different HTTP response statuses and how to handle them:

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

async function getTodos() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    if (response.ok) {
      const data = await response.json();
      console.log(data);
    } else {
      console.error('Server responded with a status:', response.status);
    }
  } catch (error) {
    console.error('Fetch failed:', error.message);
  }
}

getTodos();

Post Requests

Sending data to a server via a POST request is another common operation. To do this with node-fetch, we need to specify an additional options object:

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

async function createTodo() {
  const todo = {
    title: 'Buy milk',
    completed: false
  };
  const options = {
    method: 'POST',
    body: JSON.stringify(todo),
    headers: {'Content-Type': 'application/json'}
  };

  const response = await fetch('https://jsonplaceholder.typicode.com/todos', options);
  const data = await response.json();
  console.log(data);
}

createTodo();

Here, we’ve specified the method, headers, and body for our request. Remember that it’s essential to set the Content-Type header when sending JSON.

Advanced Usage

For more complex scenarios, such as interacting with APIs that require authentication, you may need to provide additional headers, such as Authorization headers:

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

async function getProtectedData() {
  const token = 'YOUR_TOKEN_HERE';
  const response = await fetch('http://example.com/protected-data', {
    method: 'GET',
    headers: { 'Authorization': `Bearer ${token}` }
  });
  const data = await response.json();
  console.log(data);
}

getProtectedData();

In this example, replace 'YOUR_TOKEN_HERE' with your actual API token. This is a usual practice when working with services that secure their endpoints through token-based authentication.

Finally, handling file uploads via node-fetch can be executed by sending form data. The library can also handle redirects, streams, and other advanced HTTP features, but those are beyond the scope of this basic tutorial.

Conclusion

This tutorial covered the essentials of sending HTTP requests using node-fetch in Node.js. As you can see, node-fetch provides a powerful yet straightforward interface for calling web APIs and processing their responses. By following the examples provided, you are now equipped to perform basic to moderately complex HTTP operations in your Node.js applications. Like the native Fetch API in the browser, node-fetch promotes the use of modern JavaScript async/await syntax for cleaner and more readable code. Make sure to explore the node-fetch documentation to discover the full capabilities of this handy library.