w3resource

Mastering Node.js Fetch API: A Complete Guide with Examples


Node.js Fetch API: Usage, Examples, and Explanation

The Fetch API in Node.js allows developers to perform HTTP requests to fetch resources, similar to its use in browsers. While the Fetch API is natively available in modern browsers, starting from Node.js v18, it is supported as a built-in global feature. Before Node.js v18, developers used libraries like node-fetch to mimic this behavior. This guide explains how to use the Fetch API in Node.js with detailed examples and explanations.


Syntax:

Here is the general syntax for the Fetch API:

fetch(url, {
  method: 'GET', // or POST, PUT, DELETE, etc.
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data) // for POST/PUT requests
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Using Fetch API in Node.js

1. Using Fetch API in Node.js (v18+)

Starting from Node.js v18, the Fetch API is available natively without requiring any external libraries.

Example: Basic GET Request

Code:

// Import the fetch API (if needed for earlier Node.js versions)
// Not necessary for Node.js v18+

// Define an async function to fetch data
const fetchData = async () => {
  try {
    // Fetch data from a public API
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');

    // Parse the response as JSON
    const data = await response.json();

    // Log the fetched data
    console.log('Fetched Data:', data);
  } catch (error) {
    // Log errors if the request fails
    console.error('Error fetching data:', error);
  }
};

// Call the fetch function
fetchData();

Output:

Fetched Data: { 
  "userId": 1,
  "id": 1,
  "title": "Sample Title",
  "body": "This is an example response."
}

2. Using node-fetch (for Node.js versions < 18)

For older versions of Node.js, the Fetch API is unavailable, so you must install node-fetch.

Step 1: Install node-fetch

npm install node-fetch

Example: Fetch Data Using node-fetch

Code:

// Import the node-fetch library
const fetch = require('node-fetch');

// Define an async function to fetch data
const fetchData = async () => {
  try {
    // Fetch data from an API endpoint
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');

    // Convert the response to JSON format
    const data = await response.json();

    // Log the result
    console.log('Fetched Data:', data);
  } catch (error) {
    // Handle errors
    console.error('Error fetching data:', error);
  }
};

// Call the function
fetchData();

Output:

Fetched Data: { 
  "userId": 1,
  "id": 1,
  "title": "Sample Title",
  "body": "This is an example response."
}

3. Making POST Requests with Fetch API

Fetch API can also send data to a server using the POST method.

Example: Sending POST Data

Code:

// Define an async function to send data using a POST request
const sendData = async () => {
  try {
    // Define the data to send
    const payload = { title: 'foo', body: 'bar', userId: 1 };

    // Send a POST request
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST', // Specify the request method
      headers: {
        'Content-Type': 'application/json' // Set headers for JSON data
      },
      body: JSON.stringify(payload) // Convert data to JSON string
    });

    // Parse the response
    const result = await response.json();

    // Log the server's response
    console.log('Response:', result);
  } catch (error) {
    // Handle errors
    console.error('Error sending data:', error);
  }
};

// Call the function to send data
sendData();

Output:

Response: {
  "title": "foo",
  "body": "bar",
  "userId": 1,
  "id": 101
}

Advantages of Fetch API in Node.js

    1. Native Support: Available natively from Node.js v18+.

    2. Promise-Based: Simplifies handling asynchronous requests with async/await.

    3. Lightweight: Minimal overhead compared to libraries like Axios.

    4. Cross-Compatibility: Consistent syntax between Node.js and browsers.


When to Use node-fetch or Native Fetch

  • Node.js v18 and later: Use the native Fetch API without additional libraries.
  • Node.js versions earlier than v18: Use node-fetch or similar libraries for Fetch-like functionality.


Follow us on Facebook and Twitter for latest update.