在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
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 fetch 是一個將 Fetch API 引入 Node.js 的模組。 Fetch API 是一個現代化的介面,用於在網頁瀏覽器中進行 HTTP 請求。 Node.js fetch複製了此功能,使Node.js應用程式能夠以同樣的輕鬆和簡單性執行HTTP請求。 這使得它成為已熟悉 Fetch API 的開發者或尋找在其 Node.js 應用程式中處理 HTTP 請求的簡單方法的開發者的絕佳選擇。
Node.js fetch 模擬了瀏覽器中的 Fetch API,為開發者提供了簡單且熟悉的介面。
像 Fetch API 一樣,Node.js fetch 是基於 Promise 的,使開發者能夠以更易於閱讀和管理的方式撰寫非同步代碼。
Node.js fetch 是一個簡約的函式庫,速度快且高效能。 它不會帶來較大型 HTTP 函式庫的負擔,保持您的應用程式精簡。
Node.js fetch 支援多種 HTTP 方法、標頭和回應類型,使用起來非常靈活。
它支持流響應,這對有效處理大型負載非常有用。
要開始使用Node-fetch,您需要透過 npm(Node Package Manager)安裝它。 在您的專案目錄中運行以下命令:
npm install node-fetch
以下是如何使用 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);
});
此程式碼片段展示了一個簡單的 GET 請求,用於從 API 獲取 JSON 數據。 fetch 函數返回一個會解決為回應物件的承諾。 接著,你可以呼叫回傳回應的方法,例如 json() 來解析回應內文。
Node.js fetch 還支持更多高級功能,例如進行 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);
});
此範例顯示如何使用 JSON 負載發送 POST 請求對象。 headers 選項用於指定新回應的內容類型,而 body 選項則包含序列化的 JSON 資料。
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);
});
在此範例中,響應主體被作為檔案流傳遞到伺服器,以展示如何有效處理大型響應。
在處理 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);
});
如果回應標頭狀態不在 200-299 範圍內,這裡會拋出錯誤,並且 catch 區塊會處理請求期間發生的任何錯誤,否則將返回有效的 JSON 回應。
Node fetch 是 Node.js 生態系統中用於發送 HTTP fetch 請求的熱門庫。 當與IronPDF這個強大的 PDF 生成庫結合使用時,它成為從各種網頁資源創建 PDF 的多功能工具。
IronPDF 是一個強大的程式庫,允許開發者以簡單高效的方式創建、編輯和提取 PDF 的內容。 IronPDF 提供 C#、Python、Java 和 Node.js 版本,其直觀的 API 使 PDF 操作變得簡單。
首先,您需要在您的專案中安裝IronPDF。 使用以下 npm 指令來安裝這些庫:
npm i @ironsoftware/ironpdf
讓我們來探索如何使用 Node.js fetch 搭配 IronPDF 從網路內容來源生成 PDF。
您可以利用 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!");
})();
JSON 回應輸出被優雅地映射到 HTML 表格,而IronPDF能夠準確地轉換並保留其所有樣式。
如需有關IronPDF及其功能的詳細資訊,請參閱此說明文件頁面。
Node fetch 是一個用於在 Node.js 中發出 HTTP 請求的強大而簡單的工具。 其熟悉的 API、基於承諾的方式以及輕量化特性,使其成為初學者和有經驗的開發者的絕佳選擇。 無論您是執行基本的 GET 請求還是處理具有自訂標頭的複雜 POST 請求,Node fetch 都提供了一種與 Web API 互動的簡潔高效的方法。
將Node fetch與IronPDF相結合,提供了一種強大且靈活的方法,能夠在Node.js中從各種網路內容來源生成PDF。 通過整合這兩個庫,您可以輕鬆創建利用網絡數據並生成專業 PDF 的強大應用程序。
IronPDF 起始價格為 $749。 免費體驗其強大的 PDF 生成功能。 立即試用,自己體驗不同之處!