Node.js Fetch(开发者如何使用)
Node Fetch 是 Node.js 生态系统中流行的轻量级模块,旨在使 HTTP 请求变得简单直观。它提供了一种轻量级且熟悉的方法来与 Web API 交互,灵感来自于浏览器环境中的 Fetch API。 Node-fetch 在 Node.js 中提供 Fetch API 支持,使服务工作者能够有效地处理 HTTP 头和执行 fetch HTTPS 请求。
本文将帮助您探索 Node-fetch 的关键特性和用法,提供一份面向开发人员的全面指南,以便简化他们在 Node.js 中的 HTTP 请求处理。 我们还将利用 IronPDF,一个用于 Node.js 的 PDF 库,使程序员能够创建和编辑 PDF,转换 HTML 内容为 PDF,以及更多功能。
什么是 Node.js fetch?
Node fetch 是一个为 Node.js 引入 Fetch API 的模块。 Fetch API 是一种现代化的用于发出 HTTP 请求的接口,通常在网络浏览器中使用。 Node.js fetch 复制了此功能,使 Node.js 应用程序可以同样简单地执行 HTTP 请求。 这使得它成为已经熟悉 Fetch API 或希望在他们的 Node.js 应用程序中以简洁渐进方式处理 HTTP 请求的开发人员的绝佳选择。

Node.js Fetch 的关键特性
1. 简单性和熟悉性
Node.js fetch 模仿浏览器中的 Fetch API,为开发者提供了简单而熟悉的接口。
2. 基于 Promise
如同 Fetch API,Node.js fetch 也是基于 promise 的,使开发人员能够以更可读和可管理的方式编写异步代码。
3. 轻量级
Node.js fetch 是一个极简的库,使其快速高效。 它没有较大 HTTP 库的开销,保持您的应用精简。
4. 兼容性
Node.js fetch 支持多种 HTTP 方法、头信息和响应类型,使其用途广泛。
5. 流式响应
它支持流式响应,对于高效处理大负荷的情况十分有用。
安装 Node.js Fetch
要开始使用 Node-fetch,您需要通过 NPM(Node Package Manager)安装它。 在您的项目目录中运行以下命令:
npm install node-fetchnpm install node-fetch基本用法
这是一个如何使用 Node.js fetch 发布 GET 请求的基本示例:
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);
});此代码示例展示了如何用简单的 GET 请求从 API 获取 JSON 数据。 fetch 函数返回一个解析为响应对象的 promise。 接下来,您可以调用返回响应的方法,例如 json() 来解析响应主体。
控制台输出

高级用法
Node.js fetch 还支持更多高级功能,例如发送 POST 请求、设置自定义请求头,以及处理不同的响应类型。
发起 POST 请求
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);
});此示例展示了如何以 JSON 有效负荷发送 POST 请求。 headers 选项用于指定响应的内容类型,body 选项包含序列化的 JSON 数据。
控制台输出

处理流式响应
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);
});在此示例中,将响应主体作为文件流传输到服务器,展示了如何高效处理大响应。
输出

错误处理
在处理 HTTP 请求时,正确的错误处理至关重要。 Node.js fetch 提供了一种简单明了的方法使用 promise 捕获和处理错误。
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);
});在此,如果响应状态不在 200-299 范围内,则抛出一个错误,并且 catch 块处理请求过程中发生的任何错误。否则,返回有效的 JSON 响应。
使用 Node.js fetch 和 IronPDF 在 Node.js 中生成 PDF
Node fetch 是 Node.js 生态系统中用于发起 HTTP fetch 请求的流行库。 当与IronPDF 这样强大的 PDF 生成库结合使用时,它便成为一个从各种 web 资源创建 PDF 的多功能工具。
什么是 IronPDF?
IronPDF 是一个强大的库,允许开发人员以简单高效的方式创建、编辑和提取 PDF 内容。 适用于 C#、Python、Java 和 Node.js,IronPDF 通过其直观的 API 简化了 PDF 操作。

安装 IronPDF 库
首先,您需要在您的项目中安装 IronPDF。 使用以下 npm 命令安装库:
npm i @ironsoftware/ironpdf
让我们探索如何使用 Node.js fetch 和 IronPDF 从 Web 内容源生成 PDF。
结合 Node.js fetch 和 IronPDF
您可以使用 Node.js fetch 和 IronPDF 的功能动态获取 Web 内容并生成 PDF。 例如,您可能获取 API 端点的数据,生成动态 HTML,并将其转换为 PDF。 以下示例演示了如何完成此任务:
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!");
})();输出 PDF 文件
JSON 响应输出优雅地映射到 HTML 表格中,IronPDF 准确地将其与所有样式一起转换。

结论
Node fetch 是用于在 Node.js 中发起 HTTP 请求的功能强大而简单的工具。 其熟悉的 API、基于 promise 的方法和轻量级特性使其成为初学者和经验丰富的开发者的绝佳选择。 无论您是执行基本的 GET 请求还是处理带有自定义头的复杂 POST 请求,Node fetch 都提供了一种干净高效的方式来与 Web API 交互。
将Node fetch与IronPDF结合使用,为基于 Node.js 的各个 Web 内容源生成 PDF 提供了一种功能强大且灵活的方式。 通过集成这两个库,您可以创建强大的应用程序,充分利用 web 数据并轻松生成专业的 PDF。
IronPDF 起价$799。 体验其强大的 PDF 生成功能,无风险。 立即试用,亲自见证不同之处!








