docs.rodeo

MDN Web Docs mirror

Request

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

The Request interface of the Fetch API represents a resource request.

You can create a new Request object using the {{domxref("Request.Request","Request()")}}  constructor, but you are more likely to encounter a Request object being returned as the result of another API operation, such as a service worker {{domxref("FetchEvent.request")}} .

Constructor

Instance properties

Instance methods

[!NOTE] The request body functions can be run only once; subsequent calls will reject with TypeError showing that the body stream has already used.

Examples

In the following snippet, we create a new request using the Request() constructor (for an image file in the same directory as the script), then return some property values of the request:

const request = new Request("https://www.mozilla.org/favicon.ico");

const url = request.url;
const method = request.method;
const credentials = request.credentials;

You could then fetch this request by passing the Request object in as a parameter to a {{domxref("Window/fetch", "fetch()")}}  call, for example:

fetch(request)
  .then((response) => response.blob())
  .then((blob) => {
    image.src = URL.createObjectURL(blob);
  });

In the following snippet, we create a new request using the Request() constructor with some initial data and body content for an API request which need a body payload:

const request = new Request("https://example.com", {
  method: "POST",
  body: '{"foo": "bar"}',
});

const url = request.url;
const method = request.method;
const credentials = request.credentials;
const bodyUsed = request.bodyUsed;

[!NOTE] The body can only be a {{domxref("Blob")}} , an {{jsxref("ArrayBuffer")}} , a {{jsxref("TypedArray")}} , a {{jsxref("DataView")}} , a {{domxref("FormData")}} , a {{domxref("URLSearchParams")}} , a {{domxref("ReadableStream")}} , or a {{jsxref("String")}}  object, as well as a string literal, so for adding a JSON object to the payload you need to stringify that object.

You could then fetch this API request by passing the Request object in as a parameter to a {{domxref("Window/fetch", "fetch()")}}  call, for example and get the response:

fetch(request)
  .then((response) => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error("Something went wrong on API server!");
    }
  })
  .then((response) => {
    console.debug(response);
    // …
  })
  .catch((error) => {
    console.error(error);
  });

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN