The fetch()
method is defined on the Window
object and the WorkerGlobalScope
object to initiate resource requests. It returns a Promise
object, which is resolved after the request response and returns a Response
object.
Promise<Response> fetch(input[, init])
input
: Specifies the resource to be fetched and can have the following values:
- A string containing the URL of the resource to be fetched. Some browsers accept
blob
anddata
asschemes
. - A
Request
object.
init
: An options object that includes all the request settings. The optional parameters include:
method
: The request method to be used, such asGET
orPOST
.headers
: The request headers, in the form of aHeaders
object or an object literal containingByteString
values.body
: The request body information, which can be aBlob
,BufferSource
,FormData
,URLSearchParams
, orUSVString
object. Note that theGET
orHEAD
method requests cannot contain abody
.mode
: The request mode, such ascors
,no-cors
, orsame-origin
.credentials
: The request credentials, such asomit
,same-origin
, orinclude
. This option must be provided to automatically sendcookies
within the current domain.cache
: The request cache mode:default
,no-store
,reload
,no-cache
,force-cache
, oronly-if-cached
.redirect
: Availableredirect
modes:follow
for automatic redirection,error
to automatically terminate if a redirection occurs and throw an error, ormanual
for manual redirection handling.referrer
: AUSVString
that can beno-referrer
,client
, or aURL
, with the default beingclient
.referrerPolicy
: Specifies the value of thereferer
HTTP header and can be one of the following:no-referrer
,no-referrer-when-downgrade
,origin
,origin-when-cross-origin
,unsafe-url
.integrity
: Includes thesubresource integrity
value of the request, for example:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=
.
It returns a Promise
which resolves to a Response
object.
- When a
fetch()
call receives an HTTP status code indicating an error, the returnedPromise
is not marked asreject
, even if the response HTTP status code is404
or500
. Instead, thePromise
resolves, but theok
property of the resolved value is set tofalse
only in the case of network failure or when the request is blocked. fetch()
does not accept cross-origincookies
, and it cannot establish cross-origin sessions. TheSet-Cookie
header from other domains will be ignored.fetch()
does not sendcookies
unless thecredentials
initialization option is used.
Initiating a simple resource request with fetch
returns a Promise
object, which resolves to a Response
object after the request response.
window.fetch("https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js")
.then(res => console.log(res))
Setting parameters via the init
options object allows configuration of method
, header
, body
, mode
, credentials
, cache
, redirect
, referrer
, referrerPolicy
, and integrity
.
var headers = new Headers({
"accept": "application/javascript"
});
headers.append("accept", "application/xml");
headers.set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36");
window.fetch("https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js", {
method: "GET",
headers: headers,
cache: 'no-cache',
})
.then(res => console.log(res))
Headers.append()
: Adds a value to an existingheader
or adds a newheader
with a value.Headers.delete()
: Deletes a specifiedheader
from theHeaders
object.Headers.entries()
: Returns an iterator of all key-value pairs in theHeaders
object.Headers.get()
: Returns all the values of a specified header from theHeaders
object as aByteString
.Headers.has()
: Returns a boolean value indicating whether a specifiedheader
exists in theHeaders
object.Headers.keys()
: Returns an iterator of all existingheader
names in theHeaders
object.Headers.set()
: Replaces the value of an existingheader
or adds a newheader
with a value.Headers.values()
: Returns an iterator of all the values of existingheader
s in theHeaders
object.
Handling the response data using the Response
object, including retrieving the response status and processing the response body.
window.fetch("https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js")
.then(res => res.text())
.then(data => console.log(data))
Properties and methods related to the Response
object:
Response.headers
: Read-only. Contains theHeaders
object associated with thisResponse
.Response.ok
: Read-only. Contains a boolean value indicating whether theResponse
was successful, with anHTTP
status code in the range of200-299
.Response.redirected
: Read-only. Indicates whether theResponse
is from a redirect. If so, itsURL
list will have multiple entries.Response.status
: Read-only. Contains the status code of theResponse
.Response.statusText
: Read-only. Contains the status message consistent with theResponse
status code.Response.type
: Read-only. Contains the type of theResponse
, such asbasic
orcors
.Response.url
: Read-only. Contains theURL
of theResponse
.Response.useFinalURL
: Contains a boolean value to indicate whether this is the finalURL
of theResponse
.Response.clone()
: Creates a clone of theResponse
object.Response.error()
: Returns a newResponse
object bound to a network error.Response.redirect()
: Creates a newResponse
with a differentURL
.
The Response
implements the Body
interface, and the related properties and methods can be used directly:
Body.body
: Read-only. A simple getter that exposes thebody
content as aReadableStream
type.Body.bodyUsed
: Read-only. Contains a boolean value to indicate whether theResponse
'sBody
has been read.Body.arrayBuffer()
: Reads theResponse
object, marks it as read, and returns aPromise
object parsed as anArrayBuffer
. TheResponse
objects are set asstream
mode, so they can only be read once.Body.blob()
: Reads theResponse
object, marks it as read, and returns aPromise
object parsed as aBlob
.Body.formData()
: Reads theResponse
object, marks it as read, and returns aPromise
object parsed as aFormData
.Body.json()
: Reads theResponse
object, marks it as read, and returns aPromise
object parsed as aJSON
.Body.text()
: Reads theResponse
object, marks it as read, and returns aPromise
object parsed as aUSVString
.
https://github.com/WindrunnerMax/EveryDay
https://segmentfault.com/a/1190000012740215
https://developer.mozilla.org/zh-CN/docs/Web/API/Headers
https://developer.mozilla.org/zh-CN/docs/Web/API/Response
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch