跳至頁尾內容
NODE 說明

Node.js Fetch(開發者的使用方法)

Node Fetch 是 Node.js 生態系統中的一個流行輕量模組,旨在使 HTTP 請求變得簡單且直觀。它提供了一種輕量且熟悉的方式來與網頁 API 互動,靈感來自於瀏覽器環境中的 Fetch API。 Node-fetch 在 Node.js 中提供 Fetch API 支援,使服務工作者能夠有效地處理 HTTP 標頭並執行 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 請求。 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,該 promise 解決為響應物件。 然後您可以調用返回響應的方法,如 json() 以解析響應主體。

控制台輸出

Node.js Fetch(如何為開發人員工作):圖 2 - 使用 Node.js fetch 從 API URL

進階用法

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

處理流式傳輸響應

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 提供了一種直接的方式來使用 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);
    });
JAVASCRIPT

這裡,如果響應狀態不在 200-299 範圍內,則會拋出一個錯誤,而 catch 塊處理請求期間發生的任何錯誤。否則,會返回有效的 JSON 響應。

將 Node.js fetch 與 IronPDF 結合以在 Node.js 中生成 PDF

Node fetch 是 Node.js 生態系統中用於進行 HTTP fetch 請求的流行程式庫。 當與 IronPDF 這個強大的 PDF 生成程式庫結合使用時,它成為從各種網頁資源建立 PDF 的多功能工具。

什麼是IronPDF?

IronPDF 是一個強大的程式庫,允許開發者輕鬆高效地建立、編輯和提取 PDF 內容。 IronPDF 適用於 C#、Python、Java 和 Node.js,以其直觀的 API 使 PDF 操作變得簡單。

Node.js Fetch(如何為開發人員工作):圖 5 - IronPDF for Node.js: The Node.js PDF Library

安裝 IronPDF 程式庫

首先,您需要在專案中安裝 IronPDF。 使用以下 npm 指令來安裝程式庫:

 npm i @ironsoftware/ironpdf

讓我們來探討如何使用 Node.js fetch 與 IronPDF 從網頁內容來源生成 PDF。

結合 Node.js fetch 和 IronPDF

您可以運用 Node.js fetch 和 IronPDF 的力量來動態獲取網頁內容並生成 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 精確地將其轉換為帶有所有樣式的 PDF。

Node.js Fetch(如何為開發人員工作):圖 6 - 使用 IronPDF 精確轉換為 PDF 的 HTML 字串。

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

結論

Node fetch 是在 Node.js 中進行 HTTP 請求的強大且簡單的工具。 其熟悉的 API、基於承諾的方法和輕量級自然令其成為初學者和有經驗的開發者的絕佳選擇。 無論您是在執行基本的 GET 請求還是處理帶有自定義標頭的複雜 POST 請求,Node fetch 提供了一種乾淨且高效的方式來與網頁 API 互動。

結合 Node fetchIronPDF 提供了一種強大且靈活的方式來在 Node.js 中從各種網頁內容來源生成 PDF。 透過整合這兩個程式庫,您可以輕鬆利用網頁資料建立專業 PDF 的強大應用程式。

IronPDF 從 $999 開始。 請免風險體驗其強大 PDF 生成功能。 今天就試試看,親眼目睹它的不同!

Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant擁有邁阿密大學的電腦科學學士學位,並在Iron Software擔任全端WebOps行銷工程師。從小就對程式設計有興趣,他認為計算既神秘又易於理解,成為創意和問題解決的完美媒介。

在Iron Software,Darrius喜歡創造新事物並簡化複雜的概念,使其更易於理解。作為我們的常駐開發人員之一,他還志願教學,將他的專業知識傳授給下一代。

對Darrius來說,他的工作是有意義的,因為它有價值且對社會有真正的影響。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話