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
blobanddataasschemes. - A
Requestobject.
init: An options object that includes all the request settings. The optional parameters include:
method: The request method to be used, such asGETorPOST.headers: The request headers, in the form of aHeadersobject or an object literal containingByteStringvalues.body: The request body information, which can be aBlob,BufferSource,FormData,URLSearchParams, orUSVStringobject. Note that theGETorHEADmethod 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 sendcookieswithin the current domain.cache: The request cache mode:default,no-store,reload,no-cache,force-cache, oronly-if-cached.redirect: Availableredirectmodes:followfor automatic redirection,errorto automatically terminate if a redirection occurs and throw an error, ormanualfor manual redirection handling.referrer: AUSVStringthat can beno-referrer,client, or aURL, with the default beingclient.referrerPolicy: Specifies the value of therefererHTTP header and can be one of the following:no-referrer,no-referrer-when-downgrade,origin,origin-when-cross-origin,unsafe-url.integrity: Includes thesubresource integrityvalue 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 returnedPromiseis not marked asreject, even if the response HTTP status code is404or500. Instead, thePromiseresolves, but theokproperty of the resolved value is set tofalseonly 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-Cookieheader from other domains will be ignored.fetch()does not sendcookiesunless thecredentialsinitialization 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 existingheaderor adds a newheaderwith a value.Headers.delete(): Deletes a specifiedheaderfrom theHeadersobject.Headers.entries(): Returns an iterator of all key-value pairs in theHeadersobject.Headers.get(): Returns all the values of a specified header from theHeadersobject as aByteString.Headers.has(): Returns a boolean value indicating whether a specifiedheaderexists in theHeadersobject.Headers.keys(): Returns an iterator of all existingheadernames in theHeadersobject.Headers.set(): Replaces the value of an existingheaderor adds a newheaderwith a value.Headers.values(): Returns an iterator of all the values of existingheaders in theHeadersobject.
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 theHeadersobject associated with thisResponse.Response.ok: Read-only. Contains a boolean value indicating whether theResponsewas successful, with anHTTPstatus code in the range of200-299.Response.redirected: Read-only. Indicates whether theResponseis from a redirect. If so, itsURLlist will have multiple entries.Response.status: Read-only. Contains the status code of theResponse.Response.statusText: Read-only. Contains the status message consistent with theResponsestatus code.Response.type: Read-only. Contains the type of theResponse, such asbasicorcors.Response.url: Read-only. Contains theURLof theResponse.Response.useFinalURL: Contains a boolean value to indicate whether this is the finalURLof theResponse.Response.clone(): Creates a clone of theResponseobject.Response.error(): Returns a newResponseobject bound to a network error.Response.redirect(): Creates a newResponsewith 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 thebodycontent as aReadableStreamtype.Body.bodyUsed: Read-only. Contains a boolean value to indicate whether theResponse'sBodyhas been read.Body.arrayBuffer(): Reads theResponseobject, marks it as read, and returns aPromiseobject parsed as anArrayBuffer. TheResponseobjects are set asstreammode, so they can only be read once.Body.blob(): Reads theResponseobject, marks it as read, and returns aPromiseobject parsed as aBlob.Body.formData(): Reads theResponseobject, marks it as read, and returns aPromiseobject parsed as aFormData.Body.json(): Reads theResponseobject, marks it as read, and returns aPromiseobject parsed as aJSON.Body.text(): Reads theResponseobject, marks it as read, and returns aPromiseobject 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