Node.js fetch 指的是 Node.js 內建的全域函式 fetch(),可以直接發送 HTTP 請求並取得回應,不需要額外安裝 node-fetch 或 axios。它的用法與瀏覽器的 Fetch API 相同,回傳 Promise,所以搭配 async 與 await 最順手。
白話一點,fetch() 就像請外送員去某個網址拿東西:你給網址(有時還附上訂單內容),它回來時帶回一個「包裹」(Response 物件),打開包裹才知道裡面是文字、JSON,還是一張缺貨的通知單。
本文以 Node.js 官方文件目前的 LTS 版本(v26)與 MDN 為準,範例語法在 Node.js 22 以上都能執行。
內建 fetch 的版本與背景
Node.js 官方的全域物件文件說明了 fetch() 的版本變化:
- 從 Node.js 17.5.0 與 16.15.0 開始提供。
- 18.0.0 起不再需要
--experimental-fetch旗標。 - 21.0.0 起不再標示為實驗性功能。
它的實作是 undici,也就是專為 Node.js 從頭寫的 HTTP/1.1 用戶端;要知道目前 Node.js 內建的 undici 版本,可以讀 process.versions.undici。
下面的範例為了不依賴外部網站,都先在同一支腳本裡用 node:http 啟動一個本機測試伺服器,再用 fetch() 呼叫它。伺服器的寫法可以參考 http.createServer() 的用法,本文只看 fetch() 這一側。
import http from 'node:http';
import { text } from 'node:stream/consumers';
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/users') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify([{ id: 1, name: 'Ann' }, { id: 2, name: 'Bob' }]));
} else if (url.pathname === '/posts' && req.method === 'POST') {
const data = JSON.parse(await text(req));
res.statusCode = 201;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ id: 101, ...data }));
} else if (url.pathname === '/slow') {
setTimeout(() => res.end('late'), 500);
} else if (url.pathname === '/search') {
res.end(`q=${url.searchParams.get('q')}`);
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
await new Promise((resolve) => server.listen(0, resolve));
const base = `http://localhost:${server.address().port}`;
後面每一節的程式碼,都接在這段之後執行;最後記得呼叫 server.close()。
GET 請求與讀取 JSON
fetch(url) 預設就是 GET。回傳的 Response 物件有 ok、status、statusText 與 headers,內容要用 json()、text() 等方法讀取,它們都回傳 Promise:
const res = await fetch(`${base}/users`);
console.log(res.ok, res.status, res.statusText, res.headers.get('content-type'));
console.log(await res.json());
true 200 OK application/json
[ { id: 1, name: 'Ann' }, { id: 2, name: 'Bob' } ]
POST 請求:送出 JSON
第二個參數是選項物件,用 method、headers 與 body 設定請求。送 JSON 時,要自己用 JSON.stringify() 轉成字串,並設定 Content-Type:
const created = await fetch(`${base}/posts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'foo', userId: 1 }),
});
console.log(created.status, await created.json());
201 { id: 101, title: 'foo', userId: 1 }
HTTP 錯誤狀態不會讓 fetch 失敗
這是最常見的誤解。MDN 說明:只有請求本身失敗,例如網址格式不正確或發生網路錯誤時,fetch() 的 Promise 才會被拒絕(rejected);伺服器回傳 404、500 這類錯誤狀態碼時,fetch() 仍然成功完成,回傳一個 Response,所以要自己檢查 Response.ok 或 Response.status。
const missing = await fetch(`${base}/missing`);
console.log(missing.ok, missing.status, await missing.text());
// false 404 Not Found
ok 為 true 代表狀態碼在 200 到 299 之間。常見的寫法是包成一個函式,把非 2xx 轉成例外:
async function getJson(url) {
const r = await fetch(url);
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
}
try {
await getJson(`${base}/missing`);
} catch (e) {
console.log('getJson 丟出:', e.message); // getJson 丟出: HTTP 404
}
真正的網路錯誤(例如連線被拒絕)才會讓 Promise 被拒絕,錯誤是 TypeError:
try {
await fetch('http://localhost:1/');
} catch (e) {
console.log(e.name, e.message); // TypeError fetch failed
}
查詢字串
網址的查詢參數,用 URLSearchParams 組合,會自動處理中文、空白與特殊字元的編碼:
const params = new URLSearchParams({ q: '中文 & 空白' });
console.log(await (await fetch(`${base}/search?${params}`)).text());
// q=中文 & 空白
設定逾時:AbortSignal.timeout()
要替 fetch() 設定逾時,要透過 signal 選項。Node.js 的 AbortSignal.timeout(毫秒)(Node.js 17.3.0 起提供)會回傳一個在指定時間後自動中止的訊號,傳給 fetch() 的 signal 選項即可:
try {
await fetch(`${base}/slow`, { signal: AbortSignal.timeout(100) });
} catch (e) {
console.log(e.name, e.message);
// TimeoutError The operation was aborted due to timeout
}
body 只能讀一次,需要時用 clone()
MDN 說明,同一個回應(或請求)的 body 不能讀取超過一次;要讀兩次,必須在讀取之前先呼叫 Response.clone():
const r = await fetch(`${base}/users`);
await r.json();
console.log(r.bodyUsed); // true
try {
await r.json();
} catch (e) {
console.log(e.name, e.message);
// TypeError Body is unusable: Body has already been read
}
const r2 = await fetch(`${base}/users`);
const copy = r2.clone();
console.log((await r2.json()).length, (await copy.text()).length > 0);
// 2 true
MDN 對 clone() 還有一個提醒:只消耗其中一份複製,整個 body 就會被緩衝在記憶體裡,所以不要拿它處理很大的 body。
同時發出多個請求
多個彼此獨立的請求,用 Promise.all() 同時發出,全部完成再處理:
const [a, b] = await Promise.all([
fetch(`${base}/users`),
fetch(`${base}/search?q=1`),
]);
console.log(a.status, b.status); // 200 200
server.close();
進階用法:undici
需要連線池(Pool)、串流處理等進階功能時,可以直接使用 undici 套件;Node.js 官方的 Learn 文件〈Using the Fetch API with Undici in Node.js〉有示範,其中連線池與串流的範例需要額外安裝 undici,不在本文討論範圍。
發佈留言