การทำ Outbound Requests
Global fetch ใน Node.js
หัวข้อที่มีชื่อว่า “Global fetch ใน Node.js”ตั้งแต่ Node.js 18 เป็นต้นมา fetch API มีให้ใช้ globally — ไม่ต้อง import ไม่ต้อง npm install เป็น Web Fetch API แบบเดียวกับที่ใช้ใน browser:
// ไม่ต้อง import ใน Node 18+const response = await fetch('https://api.example.com/data');const data = await response.json();นี่เป็นการปรับปรุงครั้งใหญ่จาก http.request แบบเก่าที่ต้องประกอบ chunk จาก readable stream ด้วยตนเอง
Fetch JSON จาก public API
หัวข้อที่มีชื่อว่า “Fetch JSON จาก public API”fetch คืนค่า Promise ที่ resolve เป็น Response object เรียก .json() บน response เพื่อ parse body เป็น JSON ซึ่งก็คืน Promise เช่นกัน ดังนั้นต้อง await ด้วย
Needs the Node.js runtime — open in StackBlitz to run.
การจัดการ error ด้วย fetch
หัวข้อที่มีชื่อว่า “การจัดการ error ด้วย fetch”fetch ไม่ throw เมื่อ HTTP status เป็น non-2xx คุณต้องตรวจสอบ response.ok (boolean ที่เป็น true สำหรับ status 200–299) ด้วยตนเอง:
Needs the Node.js runtime — open in StackBlitz to run.
หมายเหตุเกี่ยวกับ http.request
หัวข้อที่มีชื่อว่า “หมายเหตุเกี่ยวกับ http.request”ก่อน fetch การทำ outbound HTTP request ใน Node.js ใช้ http.request() จาก module node:http ที่เป็น lower-level API ใช้ stream คุณอาจพบใน codebase เก่า:
// pattern เก่า — เก็บ chunk ด้วยตนเองconst http = require('node:http');
http.get('http://example.com', function(res) { let body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { console.log(body); });});สำหรับ code ใหม่ ให้ใช้ global fetch — สะอาดกว่า ใช้ Promise และทำงานได้เหมือนกันทั้งใน browser และ Node