紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS Request:new Request() 建構子、屬性與 clone()

JS Request:new Request() 建構子、屬性與 clone() 特色圖片

JS Request 指的是 Fetch API 的 Request 介面,代表一個資源請求。用 new Request() 建立,把網址、方法、標頭、body 等設定包在一個物件裡,再交給 fetch() 送出。

MDN 提到,除了自己建立,也常在別的 API 的結果裡遇到它,例如 service worker 的 FetchEvent.request。

本篇只講 Request 物件本身:建構子的參數、唯讀屬性、body 的讀取方式和 clone()。fetch() 怎麼送出、HTTP 錯誤怎麼處理,以及 Request、Response、Headers 的整體關係,站上的 JS fetch() 與 JS Fetch API 兩篇有說明;回應端的 Response 物件另有專文。

語法與參數

new Request(input)
new Request(input, options)
參數說明
input要抓取的資源。可以是網址字串,相對網址以文件的 baseURI 為基準(在 worker 裡是 WorkerGlobalScope.location);也可以是另一個 Request 物件,等於複製一份
options選用,RequestInit 物件,放這個請求的自訂設定

建構子會在這些情況丟出 TypeError:網址帶有帳號密碼(例如 http://user:[email protected]),或網址無法解析。

MDN 另外列出 NotAllowedError,與 Topics API、Private State Token API 的權限政策有關,本文不展開。

RequestInit 常用選項

options 的設定,和 fetch() 第二個參數是同一種 RequestInit。MDN 的 RequestInit 頁面列出下列選項:

選項預設說明
methodGET請求方法
headers空Headers 物件,或以標頭名稱為鍵的物件字面值
body無字串、ArrayBuffer、Blob、DataView、File、FormData、TypedArray、URLSearchParams、ReadableStream
modecorssame-origin、cors、no-cors、navigate,決定跨來源行為
credentialssame-originomit、same-origin、include,是否帶 cookie 等憑證
cachedefaultdefault、no-store、reload、no-cache、force-cache、only-if-cached
redirectfollowfollow、error、manual
integrity空字串子資源完整性(SRI)值,格式 <hash-algo>-<hash-source>,雜湊演算法是 sha256、sha384 或 sha512
keepalivefalse頁面卸載後仍不中止請求,body 大小上限 64 KiB
signal無用來中止請求的 AbortSignal
priorityautohigh、low、auto,相對於同類請求的優先順序
duplex無只能是 half;body 是 ReadableStream 時必須提供

另外還有 referrer、referrerPolicy,以及 attributionReporting、browsingTopics、privateToken 等和特定隱私 API 有關的選項,本文不逐一展開。

headers 要注意:有些標頭由瀏覽器自動設定,腳本不能改(MDN 稱為 forbidden request headers);mode 是 no-cors 時,只能設 CORS-safelisted request headers。

建立請求並讀取屬性

下面的範例假設頁面網址是 https://example.org/index.html,用最簡單的方式建立請求,看各屬性的預設值:

const req = new Request("flowers.jpg");

console.log(req.url);                           // https://example.org/flowers.jpg
console.log(req.method);                        // GET
console.log(req.mode);                          // cors
console.log(req.credentials);                   // same-origin
console.log(req.cache);                         // default
console.log(req.redirect);                      // follow
console.log(req.referrer);                      // about:client
console.log(JSON.stringify(req.referrerPolicy));   // ""
console.log(JSON.stringify(req.integrity));        // ""
console.log(req.keepalive);                     // false
console.log(JSON.stringify(req.destination));      // ""
console.log(req.bodyUsed);                      // false

url 是解析成完整網址後的結果。MDN 說明,用建構子建立的請求,mode 預設是 cors;由標記語言發出的請求(例如 <img>、<script>)則多半是 no-cors。

destination 是請求要的內容類型,用 fetch() 發出時是空字串。

下表整理 MDN 列出的唯讀屬性:

屬性內容
url、method請求的網址與方法
headers對應的 Headers 物件
mode、credentials、cache、redirect對應同名的 RequestInit 選項
referrer、referrerPolicy參照來源與參照政策;referrer 是 no-referrer 時回傳空字串
integrity、keepalive子資源完整性值、是否 keepalive;integrity 只是原樣回傳,不驗證格式
destination請求的內容類型,預設空字串
signal與請求關聯的 AbortSignal
body、bodyUsedbody 的 ReadableStream,以及 body 是否已被讀過
duplex雙工模式,目前只有 half

MDN 另有 isHistoryNavigation、isReloadNavigation、targetAddressSpace 等屬性,使用情境偏窄,本文不展開。

方法的大小寫與建構時的檢查

Fetch 規範規定,method 若不分大小寫等於 DELETE、GET、HEAD、OPTIONS、POST、PUT 其中之一,會轉成大寫;其他方法名稱原樣保留,所以 patch 不會變成 PATCH。

console.log(new Request("/a", { method: "post" }).method);    // POST
console.log(new Request("/a", { method: "patch" }).method);   // patch

建構時也會做檢查。Fetch 規範規定:方法是 CONNECT、TRACE、TRACK 時丟 TypeError;方法是 GET 或 HEAD 卻帶了 body,也丟 TypeError。網址帶帳密或無法解析,同樣是 TypeError(MDN)。

const errorName = (fn) => {
  try {
    fn();
    return "no error";
  } catch (error) {
    return error.name;
  }
};

console.log(errorName(() => new Request("/a", { method: "TRACE" })));             // TypeError
console.log(errorName(() => new Request("/a", { method: "GET", body: "x" })));    // TypeError
console.log(errorName(() => new Request("http://user:[email protected]/")));   // TypeError
console.log(errorName(() => new Request("http://[bad")));                         // TypeError
console.log(errorName(() => new Request("/a", { method: "POST", body: "x" })));   // no error

傳入 Request:複製並覆蓋設定

input 傳 Request 物件時,會以它為基礎建立新的請求;options 裡設定的項目,會取代原請求對應的設定:

const oldRequest = new Request("https://example.org/issues/12959", {
  headers: { From: "[email protected]" },
});
const newRequest = new Request(oldRequest, {
  headers: { From: "[email protected]" },
});

console.log(oldRequest.headers.get("From"));   // [email protected]
console.log(newRequest.headers.get("From"));   // [email protected]

MDN 說明,這種用法為了安全做了兩個調整:原請求若來自另一個來源,referrer 會被清掉;原請求的 mode 是 navigate 時,會改成 same-origin。MDN 認為這種用法大概只在 service worker 裡有用。

另外,原請求的 body 如果已經讀過,Fetch 規範規定建構子會丟 TypeError:

const readRequest = new Request("/a", { method: "POST", body: "x" });
await readRequest.text();

console.log(errorName(() => new Request(readRequest)));   // TypeError

同一個選項若在 Request 和 fetch() 兩處都設,MDN 說明以直接傳給 fetch() 的值為準。

body 與 Content-Type

只要 body 有型別資訊,而 headers 裡沒有 Content-Type,Fetch 規範規定建構子會補上對應的值:

body 的型別補上的 Content-Type
字串text/plain;charset=UTF-8
URLSearchParamsapplication/x-www-form-urlencoded;charset=UTF-8
FormDatamultipart/form-data; boundary=…,boundary 由瀏覽器產生
Blobblob 的 type,type 為空字串時不補
ArrayBuffer、TypedArray 等不補
const textReq = new Request("/api", { method: "POST", body: "hello" });
const formReq = new Request("/api", {
  method: "POST",
  body: new URLSearchParams({ a: "1" }),
});
const jsonReq = new Request("/api", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ a: 1 }),
});

console.log(textReq.headers.get("Content-Type"));   // text/plain;charset=UTF-8
console.log(formReq.headers.get("Content-Type"));   // application/x-www-form-urlencoded;charset=UTF-8
console.log(jsonReq.headers.get("Content-Type"));   // application/json

MDN 提醒,要送 JSON 物件,得先用 JSON.stringify() 轉成字串,並自己把 Content-Type 設成 application/json。

讀取 body

Request 讀取 body 的方式有兩種。body 屬性給你一個 ReadableStream,可以自己分段讀;GET、HEAD 的請求沒有 body,body 是 null(MDN)。

另一種是呼叫下面這些非同步方法,各自回傳一個 Promise:

方法解析結果
text()字串,固定用 UTF-8 解碼
json()把 body 當 JSON 解析後的 JavaScript 值
formData()FormData 物件
arrayBuffer()ArrayBuffer
bytes()Uint8Array
blob()Blob
const postReq = new Request("/api", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ hello: "world" }),
});

console.log(new Request("/a").body);                   // null
console.log(postReq.body instanceof ReadableStream);   // true
console.log(postReq.bodyUsed);                         // false

const data = await postReq.json();

console.log(data.hello);                               // world
console.log(postReq.bodyUsed);                         // true

MDN 說明,這些讀取 body 的方法只能呼叫一次,再呼叫會以 TypeError 被拒絕,原因是 body 的串流已經用過了:

try {
  await postReq.text();
} catch (error) {
  console.log(error.name);   // TypeError
}

各方法的例外,MDN 列出的有:

  • body 已被讀過或被鎖定,或內容解碼失敗:TypeError。
  • json() 的內容無法解析成 JSON:SyntaxError。
  • formData() 的 Content-Type 不是 application/x-www-form-urlencoded 或 multipart/form-data,或內容無法解析成 FormData:TypeError。
const badJson = new Request("/api", { method: "POST", body: "not json" });

try {
  await badJson.json();
} catch (error) {
  console.log(error.name);   // SyntaxError
}

const formBody = new Request("/api", {
  method: "POST",
  body: new URLSearchParams({ name: "alice" }),
});
const form = await formBody.formData();

console.log(form.get("name"));   // alice

const plainBody = new Request("/api", { method: "POST", body: "name=alice" });

try {
  await plainBody.formData();
} catch (error) {
  console.log(error.name);   // TypeError
}

用 ReadableStream 當 body

body 傳 ReadableStream 時,duplex: "half" 必須一起設定(MDN),沒設會丟 TypeError。half 的意思是瀏覽器得先把整個請求送完,才處理回應。

const makeStream = () =>
  new ReadableStream({
    start(controller) {
      controller.enqueue(new TextEncoder().encode("chunk"));
      controller.close();
    },
  });

const streamReq = new Request("/upload", {
  method: "POST",
  body: makeStream(),
  duplex: "half",
});

console.log(streamReq.duplex);   // half
console.log(errorName(() => new Request("/upload", { method: "POST", body: makeStream() })));   // TypeError

此外,Fetch 規範規定 keepalive 為 true 時不能用 ReadableStream 當 body。

clone():複製請求

clone() 回傳一個一模一樣的新 Request。因為 body 只能讀一次,想讓同一個請求被用兩次(例如一份送出、一份留著檢查),就要先 clone():

const original = new Request("/api", { method: "POST", body: "payload" });
const copy = original.clone();

console.log(copy === original);        // false
console.log(copy.method);              // POST
console.log(await original.text());   // payload
console.log(await copy.text());       // payload

body 已經被讀過的請求不能再 clone(),會丟 TypeError;MDN 說,clone() 存在的主要原因就是讓「只能用一次」的 body 能被多次使用。

const usedReq = new Request("/api", { method: "POST", body: "x" });
await usedReq.text();

console.log(errorName(() => usedReq.clone()));   // TypeError

MDN 還提醒,和 ReadableStream.tee() 一樣,複製出來的兩個 body 以較快那一方的速度消費;較慢那一方沒讀的資料,會無上限地暫存在記憶體裡。body 很大時要留意。

如果目的是修改請求,MDN 建議改用建構子,也就是前面「傳入 Request」那一節的做法。

用 signal 中止請求

signal 選項接受 AbortController 的 signal,請求的 signal 屬性會反映中止狀態:

const controller = new AbortController();
const abortable = new Request("/api", { signal: controller.signal });

console.log(abortable.signal.aborted);   // false

controller.abort();

console.log(abortable.signal.aborted);   // true

AbortController 的完整用法與逾時的寫法,站上有專文說明。

注意事項

  1. body 只能讀一次:text()、json() 等讀取方法再次呼叫會被拒絕;要重複使用先 clone()。
  2. GET、HEAD 不能帶 body:建構時就會丟 TypeError。
  3. JSON 要自己轉字串、設標頭:body 傳字串時預設標頭是 text/plain;charset=UTF-8,送 JSON 要自己設 Content-Type。
  4. ReadableStream 要加 duplex: "half"。
  5. patch 不會自動轉大寫:只有六個常見方法會被正規化,送 PATCH 要自己寫大寫。
  6. 相對網址依文件而定:沒有文件 baseURI 的環境(例如 Node.js)傳相對網址會丟 TypeError。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data,查詢日期 2026-11-24):

  • Request:Chrome 42(40 到 41 只在 service worker 可用)、Edge 14、Firefox 39、Safari 10.1、Node.js 18.0.0、Deno 1.0。MDN 頁面標示為 Baseline「廣泛可用」,自 2017 年 3 月起各主流瀏覽器都支援。
  • body 屬性:Chrome 105、Safari 11.1、Node.js 18.0.0;Firefox 標示為 preview。
  • bytes():Chrome 132、Firefox 128、Safari 18、Node.js 22.3.0。
  • duplex:Chrome 131、Node.js 19.1.0;Firefox 標示為 preview,Safari 版本請看 MDN 相容性表。
  • keepalive:Chrome 66、Firefox 133、Safari 13、Node.js 18.0.0。

補充說明:範例在 Chrome 158 執行(頁面網址 https://example.org/index.html),請求只建立、不送出。Node.js 22 也有全域 Request,除相對網址外結果相同。屬性與例外依 MDN,方法正規化、GET 帶 body 與補 Content-Type 依 Fetch 規範。

參考資料與延伸閱讀

發佈留言