跳转到主要内容

Response

{{APIRef("Fetch API")}}{{AvailableInWorkers}}

The Response interface of the Fetch API represents the response to a request.

You can create a new Response object using the {{domxref("Response.Response", "Response()")}} constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker {{domxref("FetchEvent.respondWith")}}respondWith, or a simple {{domxref("Window/fetch", "fetch()")}}.

Constructor

  • {{domxref("Response.Response","Response()")}}
    • : Creates a new Response object.

Instance properties

Static methods

  • {{domxref("Response.error_static","Response.error()")}}
    • : Returns a new Response object associated with a network error.
  • {{domxref("Response.redirect_static", "Response.redirect()")}}
    • : Returns a new response with a different URL.
  • {{domxref("Response.json_static", "Response.json()")}}
    • : Returns a new Response object for returning the provided JSON encoded data.

Instance methods

Examples

Fetching an image

In our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an {{htmlelement("img")}}img element. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation.

You'll notice that since we are requesting an image, we need to run {{domxref("Response.blob")}}blob to give the response its correct MIME type.

const image = document.querySelector(".my-image");
fetch("flowers.jpg")
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.blob();
  })
  .then((blob) => {
    const objectURL = URL.createObjectURL(blob);
    image.src = objectURL;
  })
  .catch((error) => {
    console.error("Error fetching the image:", error);
  });

You can also use the {{domxref("Response.Response", "Response()")}} constructor to create your own custom Response object:

const response = new Response();

A PHP Call

Here we call a PHP program file that generates a JSON string, displaying the result as a JSON value.

// Function to fetch JSON using PHP
const getJSON = async () => {
  // Generate the Response object
  const response = await fetch("getJSON.php");
  if (response.ok) {
    // Get JSON value from the response body
    return response.json();
  }
  throw new Error("*** PHP file not found");
};

// Call the function and output value or error message to console
getJSON()
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}

See also