Node.js Fetch (How It Works For Developers)
Node Fetch is a popular lightweight 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.
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
Basic Usage
Here's a basic example of how to use Node.js fetch to make a GET request:
import fetch from 'node-fetch';
const url = 'https://jsonplaceholder.typicode.com/posts';
// Make a GET request to fetch data
fetch(url)
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Process the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('There has been a problem with your fetch operation:', error);
});
import fetch from 'node-fetch';
const url = 'https://jsonplaceholder.typicode.com/posts';
// Make a GET request to fetch data
fetch(url)
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Process the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('There has been a problem with your fetch operation:', error);
});
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
Advanced Usage
Node.js fetch also supports more advanced features, such as making POST requests, setting custom request headers, and handling different response types.
Making a POST Request
import fetch from 'node-fetch';
const url = 'https://jsonplaceholder.typicode.com/posts';
const data = { key: 'value' };
// Make a POST request with JSON payload
fetch(url, {
method: 'POST',
headers: {
// Specify content type as JSON
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Process the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('There has been a problem with your fetch operation:', error);
});
import fetch from 'node-fetch';
const url = 'https://jsonplaceholder.typicode.com/posts';
const data = { key: 'value' };
// Make a POST request with JSON payload
fetch(url, {
method: 'POST',
headers: {
// Specify content type as JSON
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Process the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('There has been a problem with your fetch operation:', error);
});
This example shows how to send a POST request with a JSON payload. The headers option is used to specify the content type of the response, and the body option contains the serialized JSON data.
Console Output
Handling Streaming Responses
import fetch from 'node-fetch';
import fs from 'fs';
const url = 'https://jsonplaceholder.typicode.com/posts';
// Make a GET request to fetch data and stream it to a file
fetch(url)
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Pipe the response body as a file stream to 'large-data.json'
const dest = fs.createWriteStream('./large-data.json');
response.body.pipe(dest);
})
.catch(error => {
// Handle any errors that occur during the fetch
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';
// Make a GET request to fetch data and stream it to a file
fetch(url)
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Pipe the response body as a file stream to 'large-data.json'
const dest = fs.createWriteStream('./large-data.json');
response.body.pipe(dest);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('There has been a problem with your fetch operation:', error);
});
In this example, the response body is piped to the server as a file stream, demonstrating how to handle large responses efficiently.
OUTPUT
Error Handling
Proper error handling is crucial when working with HTTP requests. Node.js fetch provides a straightforward way to catch and handle errors using promises.
fetch(url)
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Process the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('Fetch error:', error);
});
fetch(url)
.then(response => {
// Check if the response status is OK
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Process the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the fetch
console.error('Fetch error:', error);
});
Here, an error is thrown if the response 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.
Installing IronPDF Library
First, you need to install IronPDF in your project. Use the following npm command to install the library:
npm i @ironsoftware/ironpdf
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!");
})();
Output PDF
The JSON response output is elegantly mapped to the HTML table and IronPDF converts it with all its styling 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!