節點幫助

Node.js Fetch(開發者如何使用)

發佈 2024年9月29日
分享:

Node Fetch 是一個在 Node.js 生態系統中受歡迎的輕量級模組,旨在使 HTTP 請求變得簡單直觀。它提供了一種輕量且熟悉的方式來與網絡 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 請求。 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 安裝它。 (節點套件管理器). 在您的專案目錄中運行以下命令:

npm install node-fetch
npm install node-fetch
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install node-fetch
VB   C#

基本用法

以下是如何使用 Node.js fetch 發送 GET 請求的基本範例:

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); });
VB   C#

此程式碼片段展示了一個簡單的 GET 請求,用於從 API 獲取 JSON 數據。 fetch 函數返回一個 promise,該 promise 解析為 response 對象。 然後,您可以調用返回響應的方法,例如 json。()** 解析響應正文。

控制台輸出

Node.js Fetch(開發人員如何使用):圖2 - 使用Node.js fetch從API網址「https://jsonplaceholder.typicode.com/posts」進行簡單GET請求以獲取JSON數據的控制台輸出。

進階用法

Node.js fetch 還支持更多高級功能,例如進行 POST 請求、設置自定義請求標頭對象,並處理不同的響應類型。

發送 POST 請求

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); });
VB   C#

此範例顯示如何使用 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';
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); });
VB   C#

在此範例中,響應主體被作為檔案流傳遞到伺服器,以展示如何有效處理大型響應。

輸出

Node.js Fetch(開發者的運作方式):圖 4 - 輸出文件:large-data.json

錯誤處理

在處理 HTTP 請求時,正確的錯誤處理至關重要。 Node.js 提取錯誤回應提供了一種使用 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(})
VB   C#

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

在 Node.js 中使用 Node.js fetch 與 IronPDF 來生成 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:Node.js PDF 庫

安裝 IronPDF 函式庫

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

npm i @ironsoftware/ironpdf
npm i @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm i @ironsoftware/ironpdf
VB   C#

讓我們來探索如何使用 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!");
})();
'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!"); })();
VB   C#

輸出 PDF

JSON 回應輸出優雅地對應到 HTML 表格,IronPDF 能準確地將其連同所有樣式一起轉換。

Node.js Fetch(對開發人員的工作原理):圖 6 - 使用 IronPDF 準確地將 HTML 字串轉換為 PDF。

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

結論

Node fetch 是一個強大且簡單的工具,用於在 Node.js 中發送 HTTP 請求。 其熟悉的 API、基於承諾的方式以及輕量化特性,使其成為初學者和有經驗的開發者的絕佳選擇。 無論您是執行基本的 GET 請求還是使用自訂標頭處理複雜的 POST 請求,Node fetch 提供了一種清晰且有效的方式與 Web API 互動。

結合 Node fetchIronPDF 提供一種強大且靈活的方法,從 Node.js 中的各種網路內容來源生成 PDF。 通過整合這兩個庫,您可以輕鬆創建利用網絡數據並生成專業 PDF 的強大應用程序。

IronPDF 從 $749 起。免費體驗其強大的 PDF 生成功能。 今天就試試看,親自體驗這個不同之處。!

< 上一頁
Ramda JS NPM(對開發人員的運作方式)
下一個 >
Multer Node.js(開發人員如何使用)

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 npm 安裝 查看許可證 >