A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch below:

Window: fetch() method - Web APIs

Syntax
fetch(resource)
fetch(resource, options)
Parameters
resource

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

options Optional

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

Return value

A Promise that resolves to a Response object.

Exceptions
AbortError DOMException

The request was aborted due to a call to the AbortController abort() method.

NotAllowedError DOMException

Thrown if use of the Topics API is specifically disallowed by a browsing-topics Permissions Policy, and a fetch() request was made with browsingTopics: true.

TypeError

Can occur for the following reasons:

Examples

In our Fetch Request example (see Fetch Request live) we create a new Request object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run Response.blob() on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element.

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 our Fetch Request with init example (see Fetch Request init live) we do the same thing except that we pass in an options object when we invoke fetch(). In this case, we can set a Cache-Control value to indicate what kind of cached responses we're okay with:

const myImage = document.querySelector("img");
const reqHeaders = new Headers();

// A cached response is okay unless it's more than a week old
reqHeaders.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 the init object in with the Request constructor to get the same effect:

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

You can also use an object literal as headers in init:

const options = {
  headers: {
    "Cache-Control": "max-age=60480",
  },
};

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

The Using fetch article provides more examples of using fetch().

Specifications Browser compatibility

Loading…

See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.5