Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Window: fetch() method

BaselineWidely available *

Thefetch() method of theWindow interface starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.

The promise resolves to theResponse object representing the response to your request.

Afetch() promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error.Afetch() promisedoes not reject if the server responds with HTTP status codes that indicate errors (404,504, etc.).Instead, athen() handler must check theResponse.ok and/orResponse.status properties.

Thefetch() method is controlled by theconnect-src directive ofContent Security Policy rather than the directive of the resources it's retrieving.

Note:Thefetch() method's parameters are identical to those of theRequest() constructor.

Syntax

js
fetch(resource)fetch(resource, options)

Parameters

resource

This defines the resource that you wish to fetch. This can either be:

  • A string or any other object with astringifier — including aURL object — that provides the URL of the resource you want to fetch. The URL may be relative to the base URL, which is the document'sbaseURI in a window context, orWorkerGlobalScope.location in a worker context.
  • ARequest object.
optionsOptional

ARequestInit object containing any custom settings that you want to apply to the request.

Return value

APromise that resolves to aResponse object.

Exceptions

AbortErrorDOMException

The request was aborted due to a call to theAbortControllerabort() method.

NotAllowedErrorDOMException

Thrown if use of theTopics API is specifically disallowed by abrowsing-topicsPermissions Policy, and afetch() request was made withbrowsingTopics: true.

TypeError

Can occur for the following reasons:

ReasonFailing examples
Blocked by a permissions policyUse of theAttribution Reporting API is blocked by aattribution-reportingPermissions-Policy, and afetch() request was made withattributionReporting specified.
Invalid header name.
js
// space in "C ontent-Type"const headers = {  "C ontent-Type": "text/xml",  "Breaking-Bad": "<3",};fetch("https://example.com/", { headers });
Invalid header value. The header object must contain exactly two elements.
js
const headers = [  ["Content-Type", "text/html", "extra"],  ["Accept"],];fetch("https://example.com/", { headers });
Invalid URL or scheme, or using a scheme that fetch does not support, or using a scheme that is not supported for a particular request mode.
js
fetch("blob://example.com/", { mode: "cors" });
URL includes credentials.
js
fetch("https://user:password@example.com/");
Invalid referrer URL.
js
fetch("https://example.com/", { referrer: "./abc\u0000df" });
Invalid modes (navigate andwebsocket).
js
fetch("https://example.com/", { mode: "navigate" });
If the request cache mode is "only-if-cached" and the request mode is other than "same-origin".
js
fetch("https://example.com/", {  cache: "only-if-cached",  mode: "no-cors",});
If the request method is an invalid name token or one of the forbidden headers (CONNECT,TRACE orTRACK).
js
fetch("https://example.com/", { method: "CONNECT" });
If the request mode is "no-cors" and the request method is not a CORS-safe-listed method (GET,HEAD, orPOST).
js
fetch("https://example.com/", {  method: "CONNECT",  mode: "no-cors",});
If the request method isGET orHEAD and the body is non-null or not undefined.
js
fetch("https://example.com/", {  method: "GET",  body: new FormData(),});
If fetch throws a network error.

Examples

In ourFetch Request example (seeFetch Request live) wecreate a newRequest object using the relevant constructor, then fetch itusing afetch() call. Since we are fetching an image, we runResponse.blob() on the response to give it the proper MIME type so it will behandled properly, then create an Object URL of it and display it in an<img> element.

js
const myImage = document.querySelector("img");const myRequest = new Request("flowers.jpg");window  .fetch(myRequest)  .then((response) => {    if (!response.ok) {      throw new Error(`HTTP error! Status: ${response.status}`);    }    return response.blob();  })  .then((response) => {    myImage.src = URL.createObjectURL(response);  });

In ourFetch Request with init example (seeFetch Request init live) we do the same thing except that we pass in anoptions object when we invokefetch().In this case, we can set aCache-Control value to indicate what kind of cached responses we're okay with:

js
const myImage = document.querySelector("img");const reqHeaders = new Headers();// A cached response is okay unless it's more than a week oldreqHeaders.set("Cache-Control", "max-age=604800");const options = {  headers: reqHeaders,};// Pass init as an "options" object with our headers.const req = new Request("flowers.jpg", options);fetch(req).then((response) => {  // …});

You could also pass theinit object in with theRequest constructor to get the same effect:

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

You can also use an object literal asheaders ininit:

js
const options = {  headers: {    "Cache-Control": "max-age=60480",  },};const req = new Request("flowers.jpg", options);

TheUsing fetch article provides more examples of usingfetch().

Specifications

Specification
Fetch
# fetch-method

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp