Response

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

Fetch APIResponse 介面代表了一個請求會返回的回應。

你可以用 Response.Response() (en-US) 建構子創建一個新的 Response物件。但實務上碰到 Response 物件的時機,比較常出現在進行了一個 API 操作後,得到返回的 Response 物件。舉例而言,使用 service worker Fetchevent.respondWith (en-US) 或是使用單純的GlobalFetch.fetch() (en-US)

建構子

Response() (en-US)

創建一個新的 Response 物件。

屬性

Response.headers (en-US) Read only

包含與此 response 相關的 Headers (en-US) 物件。

Response.ok (en-US) Read only

無論此 response 是不是成功 ( 狀態碼 200-299 ) 都會包含一個 boolean 狀態。

Response.redirected (en-US) Read only

指出此 response 是不是個重新導向的結果,如果是的話,代表此 URL 具有一個以上的入口。

Response.status (en-US) Read only

包含此 response 的狀態碼(例如:成功時為 200 )。

Response.statusText (en-US) Read only

包含狀態碼所對應的狀態文字 (例如: OK 對應 200)。

Response.type (en-US) Read only

包含此 response 的類型 (例如: basic, cors)。

Response.url (en-US) Read only

包含此 response 的 URL。

Response.useFinalURL

包含一個 boolean 狀態,指出此 URL 是否為此 response 的最後一步。

Response 實做了Body, 所以它另有以下可用的屬性:

Body.body (en-US) Read only

A simple getter used to expose a ReadableStream (en-US) of the body contents.

Body.bodyUsed (en-US) Read only

Stores a Boolean (en-US) that declares whether the body has been used in a response yet.

方法

Response.clone() (en-US)

建立一份 Response 的複製物件。

Response.error() (en-US)

Returns a new Response object associated with a network error.

Response.redirect() (en-US)

Creates a new response with a different URL.

Response implements Body, so it also has the following methods available to it:

Body.arrayBuffer() (en-US)

Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.

Body.blob() (en-US)

Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.

Body.formData() (en-US)

Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.

Body.json() (en-US)

Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

Body.text() (en-US)

Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (en-US) (text).

範例

基本 fetch 範例 (run example live) 中,我們使用 fetch() 呼叫來得到圖片,並使用 <img> (en-US) tag 顯示。 這裡的fetch() 呼叫返回了一個 promise,它使用與資源 fetch 操作有關的 Response 進行解析。你可能有發現,由於我們要求的是一張圖片,所以需要用 Body.blob (en-US) (Response 時做了 body) 讓 response 有正確的 MIME 類型。

js
const image = document.querySelector(".my-image");
fetch("flowers.jpg")
  .then(function (response) {
    return response.blob();
  })
  .then(function (blob) {
    const objectURL = URL.createObjectURL(blob);
    image.src = objectURL;
  });

除此之外,你也能用 Response.Response() (en-US) 建構子去建立自己的客製化 Response 物件:

js
const response = new Response();

規範

Specification
Fetch Standard
# response-class

瀏覽器相容性

BCD tables only load in the browser

參考