NODE HELP

Node.js Fetch (How It Works For Developers)

Published September 29, 2024
Share:

Node Fetch is a popular light weight module in the Node.js ecosystem, designed to make HTTP requests simple and intuitive. It provides a lightweight and familiar way to interact with web APIs, inspired by the Fetch API available in the browser environment. Node-fetch provides Fetch API support in Node.js, enabling service workers to handle HTTP headers and perform fetch HTTPS requests efficiently.

This article will help you explore the key features, and usage of Node-fetch, offering a comprehensive guide for developers looking to streamline their HTTP request handling in Node.js. We will also utilize IronPDF, a PDF library for Node.js that enables programmers to create and edit PDFs, convert HTML content to PDF, and much more.

What is Node.js fetch?

Node fetch is a module that brings the Fetch API to Node.js. The Fetch API is a modern interface for making HTTP requests, commonly used in web browsers. Node.js fetch replicates this functionality, allowing Node.js applications to perform HTTP requests with the same ease and simplicity. This makes it an excellent choice for developers who are already familiar with the Fetch API or those looking for a straightforward way to handle HTTP requests in their Node.js applications.

Node.js Fetch (How It Works For Developers): Figure 1 - Node.js Fetch

Key Features of Node.js Fetch

1. Simplicity and Familiarity

Node.js fetch mimics the Fetch API found in browsers, providing a simple and familiar interface for developers.

2. Promise-based

Like the Fetch API, Node.js fetch is promise-based, enabling developers to write asynchronous code in a more readable and manageable way.

3. Lightweight

Node.js fetch is a minimalistic library, making it fast and efficient. It doesn't come with the overhead of larger HTTP libraries, keeping your application lean.

4. Compatibility

Node.js fetch supports a wide range of HTTP methods, headers, and response types, making it highly versatile.

5. Streaming

It supports streaming responses, which is useful for handling large payloads efficiently.

Installing Node.js Fetch

To get started with Node-fetch, you need to install it via npm (Node Package Manager). Run the following command in your project directory:

npm install node-fetch
npm install node-fetch
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install node-fetch
VB   C#

Basic Usage

Here's a basic example of how to use Node.js fetch to make a GET request:

import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fetch from 'node-fetch'; import fs from 'fs'; const url = 'https: fetch(url).@then(response => { if(!response.ok) { throw New @Error('Network response was @not ok'); } Return response.json(); }).@then(data => { console.log(data); }).catch(@error => { console.@error('There has been a problem @with your fetch operation:', @error); });
VB   C#

This code snippet demonstrates a simple GET request to fetch JSON data from an API. The fetch function returns a promise that resolves to the response object. You can then call methods that return responses, like json() to parse the response body.

Console Output

Node.js Fetch (How It Works For Developers): Figure 2 - Console output for a simple GET request to fetch JSON data from an API URL "https://jsonplaceholder.typicode.com/posts" using Node.js fetch.

Advanced Usage

Node.js fetch also supports more advanced features, for instance, such as making POST requests, setting custom request headers object, and handling different response types.

Making a POST Request

import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
const data = { key: 'value' };
fetch(url, {
    method: 'POST',
    // Content Type Header
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
const data = { key: 'value' };
fetch(url, {
    method: 'POST',
    // Content Type Header
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fetch from 'node-fetch'; import fs from 'fs'; const url = 'https: const data = { key: 'value' }; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).@then(response => { if(!response.ok) { throw New @Error('Network response was @not ok'); } Return response.json(); }).@then(data => { console.log(data); }).catch(@error => { console.@error('There has been a problem @with your fetch operation:', @error); });
VB   C#

This example shows how to send a POST request object with a JSON payload. The headers option is used to specify the content type of new response, and the body option contains the serialized JSON data.

Console Output

Node.js Fetch (How It Works For Developers): Figure 3 - Console output for a POST request object sent to URL "https://jsonplaceholder.typicode.com/posts" using Node.js fetch

Handling Streaming Responses

import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const dest = fs.createWriteStream('./large-data.json');
        response.body.pipe(dest);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const dest = fs.createWriteStream('./large-data.json');
        response.body.pipe(dest);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
    });
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fetch from 'node-fetch'; import fs from 'fs'; const url = 'https: fetch(url).@then(response => { if(!response.ok) { throw New @Error('Network response was @not ok'); } const dest = fs.createWriteStream('./large-data.json'); response.body.pipe(dest); }).catch(@error => { console.@error('There has been a problem @with your fetch operation:', @error); });
VB   C#

In this example, the response body is piped to the server as a file stream, demonstrating how to handle large responses efficiently.

OUTPUT

Node.js Fetch (How It Works For Developers): Figure 4 - Output file: large-data.json

Error Handling

Proper error handling is crucial when working with HTTP requests. Node.js fetch error response provides a straightforward way to catch and handle errors using promises.

fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Fetch error:', error);
    });
fetch(url)
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Fetch error:', error);
    });
fetch(url).then(Function(response)
	If Not response.ok Then
		Throw New [Error](`HTTP [error](Not status):= ${response.status}`)
	End If
	Return response.json()
End Function).then(Sub(data)
	console.log(data)
End Sub).catch(Function([error]) {console.error(})
VB   C#

Here, an error is thrown if the response headers status is not in the range 200-299, and the catch block handles any errors that occur during the request otherwise the valid JSON response is returned.

Using Node.js fetch with IronPDF to Generate PDFs in Node.js

Node fetch is a popular library in the Node.js ecosystem for making HTTP fetch requests. When combined with IronPDF, a powerful PDF generation library, it becomes a versatile tool for creating PDFs from various web resources.

What is IronPDF?

IronPDF is a robust library that allows developers to create, edit, and extract content from PDFs in a straightforward and efficient manner. Available for C#, Python, Java and Node.js, IronPDF makes PDF manipulation simple with its intuitive API.

Node.js Fetch (How It Works For Developers): Figure 5 - IronPDF for Node.js: The Node.js PDF Library

Installing IronPDF Library

First, you need to install IronPDF in your project. Use the following npm commands to install these libraries:

npm i @ironsoftware/ironpdf
npm i @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm i @ironsoftware/ironpdf
VB   C#

Let's explore how to use Node.js fetch with IronPDF to generate PDFs from web content sources.

Combining Node.js fetch and IronPDF

You can leverage the power of both Node.js fetch and IronPDF to fetch web content dynamically and generate PDFs. For example, you might fetch an API endpoint's data, generate dynamic HTML, and convert it to a PDF. The following example demonstrates how you can achieve this task:

import fetch from 'node-fetch';
import { PdfDocument } from '@ironsoftware/ironpdf';
(async () => {
    // Replace the apiUrl with the actual Url
    const apiUrl = "https://jsonplaceholder.typicode.com/posts";
    // Fetch data from API
    const response = await fetch(apiUrl);
    const data = await response.json();
    // Create dynamic HTML content with a table
    const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Data Report</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 40px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                }
                table, th, td {
                    border: 1px solid black;
                }
                th, td {
                    padding: 10px;
                    text-align: left;
                }
                th {
                    background-color: #f2f2f2;
                }
                h1 {
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Data Report</h1>
            <table>
                <tr>
                    <th>User ID</th>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                </tr>
                ${data.map(item => `
                    <tr>
                        <td>${item.userId}</td>
                        <td>${item.id}</td>
                        <td>${item.title}</td>
                        <td>${item.body}</td>
                    </tr>
                `).join('')}
            </table>
        </body>
        </html>
    `;
    // Generate PDF from the HTML string
    const pdfFromHtmlString = await PdfDocument.fromHtml(htmlContent);
    await pdfFromHtmlString.saveAs("dynamic_report.pdf");
    console.log("PDF generated from API data successfully!");
})();
import fetch from 'node-fetch';
import { PdfDocument } from '@ironsoftware/ironpdf';
(async () => {
    // Replace the apiUrl with the actual Url
    const apiUrl = "https://jsonplaceholder.typicode.com/posts";
    // Fetch data from API
    const response = await fetch(apiUrl);
    const data = await response.json();
    // Create dynamic HTML content with a table
    const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Data Report</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 40px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                }
                table, th, td {
                    border: 1px solid black;
                }
                th, td {
                    padding: 10px;
                    text-align: left;
                }
                th {
                    background-color: #f2f2f2;
                }
                h1 {
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Data Report</h1>
            <table>
                <tr>
                    <th>User ID</th>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                </tr>
                ${data.map(item => `
                    <tr>
                        <td>${item.userId}</td>
                        <td>${item.id}</td>
                        <td>${item.title}</td>
                        <td>${item.body}</td>
                    </tr>
                `).join('')}
            </table>
        </body>
        </html>
    `;
    // Generate PDF from the HTML string
    const pdfFromHtmlString = await PdfDocument.fromHtml(htmlContent);
    await pdfFromHtmlString.saveAs("dynamic_report.pdf");
    console.log("PDF generated from API data successfully!");
})();
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fetch from 'node-fetch'; import { PdfDocument } from '@ironsoftware/ironpdf'; (async() => { const apiUrl = "https://jsonplaceholder.typicode.com/posts"; const response = await fetch(apiUrl); const data = await response.json(); const htmlContent = ` <!DOCTYPE html> <html> <head> <title> Data Report</title> <style> body { font-family: Arial, sans-serif; margin: 40px; } table { width: 100%; border-collapse: collapse; } table, th, td { border: 1px solid black; } th, td { padding: 10px; text-align: left; } th { background-color: #f2f2f2; } h1 { text-align: center; } </style> </head> <body> <h1> Data Report</h1> <table> <tr> <th> User ID</th> <th> ID</th> <th> Title</th> <th> Body</th> </tr> ${data.map(item => ` <tr> <td> ${item.userId}</td> <td> ${item.id}</td> <td> ${item.title}</td> <td> ${item.body}</td> </tr> `).join('')} </table> </body> </html> `; const pdfFromHtmlString = await PdfDocument.fromHtml(htmlContent); await pdfFromHtmlString.saveAs("dynamic_report.pdf"); console.log("PDF generated from API data successfully!"); })();
VB   C#

Output PDF

The JSON response output is elegantly mapped to the HTML table and IronPDF converts it with all its styling accurately.

Node.js Fetch (How It Works For Developers): Figure 6 - HTML string converted to PDF using IronPDF accurately.

For more details on IronPDF and its functionalities, please refer to this documentation page.

Conclusion

Node fetch is a powerful yet simple tool for making HTTP requests in Node.js. Its familiar API, promise-based approach, and lightweight nature make it an excellent choice for both beginners and experienced developers. Whether you are performing basic GET requests or handling complex POST requests with custom headers, Node fetch provides a clean and efficient way to interact with web APIs.

Combining Node fetch with IronPDF provides a powerful and flexible way to generate PDFs from various web content sources in Node.js. By integrating these two libraries, you can create robust applications that leverage web data and generate professional PDFs with ease.

IronPDF starting at $749. Experience its powerful PDF generation features risk-free. Give it a try today and see the difference for yourself!

< PREVIOUS
Ramda JS NPM (How It Works For Developers)
NEXT >
Multer Node.js (How It Works For Developers)

Ready to get started? Version: 2024.11 just released

Free npm Install View Licenses >