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

建構子

Response()

創建一個新的 Response 物件。

屬性

Response.headers Read only

包含與此 response 相關的 Headers 物件。

Response.ok Read only

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

Response.redirected Read only

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

Response.status Read only

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

Response.statusText Read only

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

Response.type Read only

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

Response.url Read only

包含此 response 的 URL。

Response.useFinalURL

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

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

Body.body Read only

A simple getter used to expose a ReadableStream of the body contents.

Body.bodyUsed Read only

Stores a Boolean that declares whether the body has been used in a response yet.

方法

Response.clone()

建立一份 Response 的複製物件。

Response.error()

Returns a new Response object associated with a network error.

Response.redirect()

Creates a new response with a different URL.

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

Body.arrayBuffer()

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

Body.blob()

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

Body.formData()

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

Body.json()

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()

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

範例

基本 fetch 範例 (run example live) 中,我們使用 fetch() 呼叫來得到圖片,並使用 <img> tag 顯示。 這裡的fetch() 呼叫返回了一個 promise,它使用與資源 fetch 操作有關的 Response 進行解析。你可能有發現,由於我們要求的是一張圖片,所以需要用 Body.blob (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() 建構子去建立自己的客製化 Response 物件:

js
const response = new Response();

規範

Specification
Fetch Standard
# response-class

瀏覽器相容性

BCD tables only load in the browser

參考