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 模仿了瀏覽器中的 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-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,該 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 請求的函式庫。 結合功能強大的 PDF 生成庫IronPDF ,它變成了一個可以從各種網頁資源創建 PDF 的多功能工具。
IronPDF是什麼?
IronPDF是一個強大的庫,它允許開發人員以簡單且有效率的方式建立、編輯 PDF 和從 PDF 中提取內容。 IronPDF支援 C#、Python、Java 和Node.js ,其直覺的 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。 透過整合這兩個庫,您可以創建強大的應用程序,利用網路數據並輕鬆生成Professional的PDF 文件。
IronPDF從 $999 開始。 免費體驗其強大的PDF生成功能。 今天就來試試,親眼見證它的不同!







