Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. RequestInit

RequestInit

TheRequestInit dictionary of theFetch API represents the set of options that can be used to configure afetch request.

You can pass aRequestInit object into theRequest() constructor, or directly into thefetch() function call.

You can also construct aRequest with aRequestInit, and pass theRequest to afetch() call along with anotherRequestInit. If you do this, and the same option is set in both places, then the value passed directly intofetch() is used.

Instance properties

attributionReportingOptionalExperimental

Indicates that you want the request's response to be able to register a JavaScript-basedattribution source orattribution trigger.attributionReporting is an object containing the following properties:

eventSourceEligible

A boolean. If set totrue, the request's response is eligible to register an attribution source. If set tofalse, it isn't.

triggerEligible

A boolean. If set totrue, the request's response is eligible to register an attribution trigger. If set tofalse, it isn't.

See theAttribution Reporting API for more details.

bodyOptional

The request body contains content to send to the server, for example in aPOST orPUT request. It is specified as an instance of any of the following types:

SeeSetting a body for more details.

browsingTopicsOptionalExperimental

A boolean specifying that the selected topics for the current user should be sent in aSec-Browsing-Topics header with the associated request.

SeeUsing the Topics API for more details.

cacheOptional

Thecache mode you want to use for the request. This may be any one of the following values:

default

The browser looks in its HTTP cache for a response matching the request.

  • If there is a match and it isfresh, it will be returned from the cache.
  • If there is a match but it isstale, the browser will make aconditional request to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated.
  • If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
no-store

The browser fetches the resource from the remote server without first looking in the cache,and will not update the cache with the downloaded resource.

reload

The browser fetches the resource from the remote server without first looking in the cache,but then will update the cache with the downloaded resource.

no-cache

The browser looks in its HTTP cache for a response matching the request.

  • If there is a match,fresh or stale, the browser will make aconditional request to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated.
  • If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
force-cache

The browser looks in its HTTP cache for a response matching the request.

  • If there is a match,fresh or stale, it will be returned from the cache.
  • If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
only-if-cached

The browser looks in its HTTP cache for a response matching the request.Experimental

The"only-if-cached" mode can only be used if the request'smode is"same-origin". Cached redirects will be followed if the request'sredirect property is"follow" and the redirects do not violate the"same-origin" mode.

credentialsOptional

Controls whether or not the browser sends credentials with the request, as well as whether anySet-Cookie response headers are respected. Credentials are cookies,TLS client certificates, or authentication headers containing a username and password. This option may be any one of the following values:

omit

Never send credentials in the request or include credentials in the response.

same-origin

Only send and include credentials for same-origin requests.

include

Always include credentials, even for cross-origin requests.

Including credentials in cross-origin requests can make a site vulnerable toCSRF attacks, so even ifcredentials is set toinclude, the server must also agree to their inclusion by including theAccess-Control-Allow-Credentials in its response. Additionally, in this situation the server must explicitly specify the client's origin in theAccess-Control-Allow-Origin response header (that is,* is not allowed).

SeeIncluding credentials for more details.

Defaults tosame-origin.

duplexOptionalExperimental

Controls duplex behavior of the request. If this is present it must have the valuehalf, meaning that the browser must send the entire request before processing the response.

This option must be present whenbody is aReadableStream.

headersOptional

Any headers you want to add to your request, containedwithin aHeaders object or an object literal whose keys are the names of headers and whose values are the header values.

Many headers are set automatically by the browser and can't be set by a script: these are calledForbidden request headers.

If themode option is set tono-cors, you can only setCORS-safelisted request headers.

SeeSetting headers for more details.

integrityOptional

Contains thesubresource integrityvalue of the request.

This will be checked when the resource is fetched, just as it would be when theintegrity attribute is set on a<script> element. The browser will compute thehash of the fetched resource using the specified algorithm, and if the result does not match the value specified, the browser will reject the fetch request with a network error.

The format of this option is<hash-algo>-<hash-source> where:

  • <hash-algo> is one of the following values:sha256,sha384, orsha512
  • <hash-source> is theBase64-encoding of the result of hashing the resource with the specified hash algorithm.

Defaults to an empty string.

keepaliveOptional

A boolean.When set totrue, the browser will not abort the associated request if the page that initiated it is unloaded before the request is complete.This enables afetch() request to send analytics at the end of a session even if the user navigates away from or closes the page.

This has some advantages over usingNavigator.sendBeacon() for the same purpose.For example, you can use HTTP methods other thanPOST, customize request properties, and access the server response via the fetchPromise fulfillment.It is also available inservice workers.

The body size forkeepalive requests is limited to 64 kibibytes.

Defaults tofalse.

methodOptional

Therequest method.

Defaults toGET.

modeOptional

Sets cross-origin behavior for the request. One of the following values:

same-origin

Disallows cross-origin requests. If asame-origin request is sent to a different origin, the result is a network error.

cors

If the request is cross-origin then it will use theCross-Origin Resource Sharing (CORS) mechanism. OnlyCORS-safelisted response headers are exposed in the response.

no-cors

Disables CORS for cross-origin requests. This option comes with the following restrictions:

  • The method may only be one ofHEAD,GET orPOST.
  • The headers may only beCORS-safelisted request headers, with the additional restriction that theRange header is also not allowed. This also applies to any headers added by service workers.
  • The response isopaque, meaning that its headers and body are not available to JavaScript, and itsstatus code is always0.

The main application forno-cors is for a service worker: although the response to ano-cors request can't be read by JavaScript, it can be cached by a service worker and then used as a response to an intercepted fetch request. Note that in this situation you don't know whether the request succeeded or not, so you should adopt a caching strategy which enables the cached response to be updated from the network (such ascache first with cache refresh).

navigate

Used only by HTML navigation. Anavigate request is created only while navigating between documents.

SeeMaking cross-origin requests for more details.

Defaults tocors.

priorityOptional

Specifies the priority of the fetch request relative to other requests of the same type. Must be one of the following:

high

A high priority fetch request relative to other requests of the same type.

low

A low priority fetch request relative to other requests of the same type.

auto

No user preference for the fetch priority.It is used if no value is set or if an invalid value is set.

Defaults toauto.

redirectOptional

Determines the browser's behavior in case the server replies with aredirect status. One of the following values:

follow

Automatically follow redirects.

error

Reject the promise with a network error when a redirect status is returned.

manual

Return a response with almost all fields filtered out, to enable a service worker to store the response and later replay it.

Defaults tofollow.

referrerOptional

A string specifying the value to use for the request'sReferer header. One of the following:

A same-origin relative or absolute URL

Set theReferer header to the given value. Relative URLs are resolved relative to the URL of the page that made the request.

An empty string

Omit theReferer header.

about:client

Set theReferer header to the default value for the context of the request (for example, the URL of the page that made the request).

Defaults toabout:client.

referrerPolicyOptional

A string that sets a policy for theReferer header. The syntax and semantics of this option are exactly the same as for theReferrer-Policy header.

signalOptional

AnAbortSignal. If this option is set, the request can be canceled by callingabort() on the correspondingAbortController.

Examples

Passing options intofetch()

In this example we pass themethod,body, andheaders options directly into thefetch() method call:

js
async function post() {  const response = await fetch("https://example.org/post", {    method: "POST",    body: JSON.stringify({ username: "example" }),    headers: {      "Content-Type": "application/json",    },  });  console.log(response.status);}

Passing options into theRequest() constructor

In this example we create aRequest, passing the same set of options into its constructor, and then pass the request intofetch():

js
async function post() {  const request = new Request("https://example.org/post", {    method: "POST",    body: JSON.stringify({ username: "example" }),    headers: {      "Content-Type": "application/json",    },  });  const response = await fetch(request);  console.log(response.status);}

Passing options into bothRequest() andfetch()

In this example we create aRequest, passing themethod,headers, andbody options into its constructor. We then pass the request intofetch() along withbody andreferrer options:

js
async function post() {  const request = new Request("https://example.org/post", {    method: "POST",    headers: {      "Content-Type": "application/json",    },    body: JSON.stringify({ username: "example1" }),  });  const response = await fetch(request, {    body: JSON.stringify({ username: "example2" }),    referrer: "",  });  console.log(response.status);}

In this case the request will be sent with the following options:

  • method: "POST"
  • headers: {"Content-Type": "application/json"}
  • body: '{"username":"example2"}'
  • referrer: ""

Specifications

Specification
Fetch
# requestinit

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp