Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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 mimics the Fetch API found in browsers, providing a simple and familiar interface for developers.
Like the Fetch API, Node.js fetch is promise-based, enabling developers to write asynchronous code in a more readable and manageable way.
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.
Node.js fetch supports a wide range of HTTP methods, headers, and response types, making it highly versatile.
It supports streaming responses, which is useful for handling large payloads efficiently.
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
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); });
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.
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.
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); });
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.
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); });
In this example, the response body is piped to the server as a file stream, demonstrating how to handle large responses efficiently.
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(})
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.
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.
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.
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
Let's explore how to use Node.js fetch with IronPDF to generate PDFs from web content sources.
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!"); })();
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.
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!
9 .NET API products for your office documents