跳過到頁腳內容
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是將 Fetch API 引入 Node.js 的模組。 Fetch API 是一個用於發出 HTTP 請求的現代接口,常用於 Web 瀏覽器。 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. 基於承諾

與 Fetch API 類似,Node.js fetch 是基於 Promise 的,使開發人員能夠以更易於閱讀、更易於管理的方式編寫非同步程式碼。

3. 輕便

Node.js fetch 是一個極簡的函式庫,因此速度快、效率高。 它沒有大型 HTTP 庫帶來的額外開銷,可讓您的應用程式保持輕量級。

4. 相容性

Node.js fetch 支援多種 HTTP 方法、標頭和回應類型,使其具有很高的通用性。

5. 串流媒體

它支援串流響應,這對於高效處理大型有效載荷非常有用。

安裝 Node.js Fetch

要開始使用Node-fetch ,您需要透過 npm(Node 套件管理器)安裝它。 在專案目錄中執行以下命令:

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,該 Promise 會解析為回應物件。 然後,您可以呼叫回傳回應的方法,例如json()來解析回應正文。

控制台輸出

Node.js Fetch(開發者如何操作):圖 2 - 使用 Node.js fetch 從 API URL"https://jsonplaceholder.typicode.com/posts"取得 JSON 資料的簡單 GET 要求的控制台輸出。

進階用法

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 請求的函式庫。 結合功能強大的 PDF 生成庫IronPDF ,它變成了一個可以從各種網頁資源創建 PDF 的多功能工具。

什麼是 IronPDF?

IronPDF是一個強大的庫,它允許開發人員以簡單且有效率的方式建立、編輯 PDF 和從 PDF 中提取內容。 IronPDF 提供 C#、Python、Java 和 Node.js 版本,其直覺的 API 讓 PDF 操作變得簡單。

Node.js Fetch(開發者使用方法):圖 5 - IronPDF for Node.js:Node.js 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!");
})();
JAVASCRIPT

輸出 PDF

JSON 回應輸出被優雅地對應到 HTML 表格, IronPDF可以準確地將其及其所有樣式進行轉換。

Node.js Fetch(開發者如何理解其工作原理):圖 6 - 使用 IronPDF 準確地將 HTML 字串轉換為 PDF。

有關IronPDF及其功能的更多詳細信息,請參閱此文件頁面

結論

Node fetch是一個功能強大且簡單的工具,用於在 Node.js 中發出 HTTP 請求。 它熟悉的 API、基於 Promise 的方法以及輕量級的特性,使其成為初學者和經驗豐富的開發人員的絕佳選擇。 無論您是執行基本的 GET 請求還是處理帶有自訂標頭的複雜 POST 請求, Node fetch都提供了一種簡潔高效的方式來與 Web API 進行互動。

Node fetchIronPDF結合使用,可以在 Node.js 中以強大且靈活的方式從各種 Web 內容來源產生 PDF。 透過整合這兩個庫,您可以創建強大的應用程序,利用網路數據並輕鬆生成專業的 PDF 文件。

IronPDF起價$799 。 免費體驗其強大的PDF生成功能。 今天就來試試,親眼見證它的不同!

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。