NODE 說明 Node.js Fetch(開發者的使用方法) Darrius Serrant 更新日期:6月 22, 2025 Download IronPDF npm 下載 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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 或尋求簡便方式來處理 HTTP 請求的 Node.js 開發者的絕佳選擇。 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 此代碼片段演示了一個從 API 獲取 JSON 資料的簡單 GET 請求。 fetch 函數返回一個解析為響應對象的 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); }); JAVASCRIPT 此範例顯示如何使用 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); }); JAVASCRIPT 在此範例中,響應主體被導入服務器作為檔案串流,演示如何有效地處理大型響應。 輸出 錯誤處理 在處理 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 中使用 Node.js fetch 和 IronPDF 生成 PDF Node fetch 是 Node.js 生態系統中一個用於進行 HTTP 提取請求的流行庫。 當與功能強大的 PDF 生成庫 IronPDF 結合使用時,它成為一個從各種 Web 資源創建 PDF 的多功能工具。 什麼是 IronPDF? IronPDF 是一個強大的庫,允許開發者以簡單且高效的方式創建、編輯和提取 PDF 的內容。 可用於 C#、Python、Java 和 Node.js,IronPDF 憑藉其直觀的 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!"); })(); JAVASCRIPT 輸出 PDF JSON 響應輸出被優雅地映射到 HTML 表格中,並由 IronPDF 精確地轉換。 For more details on IronPDF and its functionalities, please refer to this documentation page. 結論 Node fetch 是一個強大但簡單的工具,用於在 Node.js 中發送 HTTP 請求。 其熟悉的 API、基於 Promise 的方法和輕量級特性使其成為初學者和資深開發者的絕佳選擇。 無論你是在執行基本的 GET 請求還是處理帶有自定義標頭的複雜 POST 請求,Node fetch 提供了一種乾淨且高效的方式與 Web API 進行互動。 Combining Node fetch with IronPDF provides a powerful and flexible way to generate PDFs from various web content sources in Node.js. 通過整合這兩個庫,你可以創建強大的應用,巧妙地運用 Web 資料並輕鬆生成專業的 PDF。 IronPDF 起價 $799。 感受其強大的 PDF 生成功能並無風險。 立即試用,親自體驗其優勢! Darrius Serrant 立即與工程團隊聊天 全棧軟件工程師 (WebOps) Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。 相關文章 更新日期 7月 28, 2025 linkify-react(使用方法:開發者指南) Linkify React 是一個輕量和容易使用的 npm 套件,能自動將含有 URLs 的純文本轉換 閱讀更多 更新日期 6月 22, 2025 next-auth NPM(開發者的使用方法) NextAuth.js 是開放源代碼驗證庫為 Next.js 應用程式專門提供實現身份驗證的一種靈活且安全的方法。 閱讀更多 更新日期 6月 22, 2025 Koa node js(開發者的使用方法) Koa.js 是一個為 Node.js 的生成 Web 框架,擅長支持异步功能,讓開發人員可以輕松編寫非同步中間件。 閱讀更多 Ramda JS NPM(開發者的使用方法)Multer Node.js(開發者的使用...
更新日期 6月 22, 2025 next-auth NPM(開發者的使用方法) NextAuth.js 是開放源代碼驗證庫為 Next.js 應用程式專門提供實現身份驗證的一種靈活且安全的方法。 閱讀更多
更新日期 6月 22, 2025 Koa node js(開發者的使用方法) Koa.js 是一個為 Node.js 的生成 Web 框架,擅長支持异步功能,讓開發人員可以輕松編寫非同步中間件。 閱讀更多