跳至页脚内容
NODE 帮助

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

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-fetch
npm install node-fetch
SHELL

基本用法

这是一个如何使用 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);
    });
JAVASCRIPT

此代码示例展示了如何用简单的 GET 请求从 API 获取 JSON 数据。 fetch 函数返回一个解析为响应对象的 promise。 接下来,您可以调用返回响应的方法,例如 json() 来解析响应主体。

控制台输出

Node.js Fetch(对开发者的工作原理):图 2 - 使用 Node.js fetch 对 API URL https://jsonplaceholder.typicode.com/posts 的简单 GET 请求获取 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);
    });
JAVASCRIPT

此示例展示了如何以 JSON 有效负荷发送 POST 请求。 headers 选项用于指定响应的内容类型,body 选项包含序列化的 JSON 数据。

控制台输出

Node.js Fetch(对开发者的工作原理):图 3 - 使用 Node.js fetch 向 URL https://jsonplaceholder.typicode.com/posts 发送的 POST 请求对象的控制台输出

处理流式响应

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);
    });
JAVASCRIPT

在此示例中,将响应主体作为文件流传输到服务器,展示了如何高效处理大响应。

输出

Node.js Fetch(对开发者的工作原理):图 4 - 输出文件:large-data.json

错误处理

在处理 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);
    });
JAVASCRIPT

在此,如果响应状态不在 200-299 范围内,则抛出一个错误,并且 catch 块处理请求过程中发生的任何错误。否则,返回有效的 JSON 响应。

使用 Node.js fetch 和 IronPDF 在 Node.js 中生成 PDF

Node fetch 是 Node.js 生态系统中用于发起 HTTP fetch 请求的流行库。 当与IronPDF 这样强大的 PDF 生成库结合使用时,它便成为一个从各种 web 资源创建 PDF 的多功能工具。

什么是 IronPDF? [**IronPDF**](/nodejs/) 是一个强大的库,允许开发人员以简单高效的方式创建、编辑和提取 PDF 内容。 适用于 C#、Python、Java 和 Node.js,IronPDF 通过其直观的 API 简化了 PDF 操作。 ![Node.js Fetch(对开发者的工作原理):图 5 - IronPDF for Node.js: The Node.js PDF Library](/static-assets/pdf/blog/node-fetch/node-fetch-5.webp) ### 安装 IronPDF 库 首先,您需要在您的项目中安装 [**IronPDF**](/nodejs/)。 使用以下 npm 命令安装库: ```shell :ProductInstall ``` 让我们探索如何使用 Node.js fetch 和 IronPDF 从 Web 内容源生成 PDF。 ## 结合 Node.js fetch 和 IronPDF 您可以使用 Node.js fetch 和 IronPDF 的功能动态获取 Web 内容并生成 PDF。 例如,您可能获取 API 端点的数据,生成动态 HTML,并[**将其转换为 PDF**](/nodejs/examples/using-html-to-create-a-pdf/)。 以下示例演示了如何完成此任务: ```javascript 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 = ` Data Report

Data Report

${data.map(item => ` `).join('')}
User ID ID Title Body
${item.userId} ${item.id} ${item.title} ${item.body}
`; // 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.js Fetch(对开发者的工作原理):图 6 - 使用 IronPDF 准确转换为 PDF 的 HTML 字符串。](/static-assets/pdf/blog/node-fetch/node-fetch-6.webp) For more details on [**IronPDF**](/nodejs/) and its functionalities, please refer to this [**documentation page**](/nodejs/docs/). ## 结论 [**Node fetch**](https://www.npmjs.com/package/node-fetch) 是用于在 Node.js 中发起 HTTP 请求的功能强大而简单的工具。 其熟悉的 API、基于 promise 的方法和轻量级特性使其成为初学者和经验丰富的开发者的绝佳选择。 无论您是执行基本的 GET 请求还是处理带有自定义头的复杂 POST 请求,**Node fetch** 都提供了一种干净高效的方式来与 Web API 交互。 Combining [**Node fetch**](https://github.com/node-fetch/node-fetch) with [**IronPDF**](/nodejs/) provides a powerful and flexible way to generate PDFs from various web content sources in Node.js. 通过集成这两个库,您可以创建强大的应用程序,充分利用 web 数据并轻松生成专业的 PDF。 [**IronPDF**](licensing) 起价$799。 体验其强大的 PDF 生成功能,无风险。 立即试用,亲自见证不同之处!
Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。