The Fetch notes
concept
// Fetch provides a generic definition of Request and Response objects.
// It also provides a new definition for related concepts, replacing their original categorical definition.
Fetch () must take one argument (the path to the resource).
// Whether the request is successful or not, it returns a Promise object.
// The Fetch API provides a global Fetch () method that provides a simple, reasonable way to Fetch resources across a network.
// This functionality was previously implemented using XMLHttpRequest.
Copy the code
The FETCH specification differs from jquery.Ajax () in three main ways:
- When an HTTP status code representing an error is received, the Promise returned from fetch() is not marked as reject, even if the HTTP status code of the response is 404 or 505. Instead, it marks the Promise state as resolve and reject only when the network fails or the request is blocked.
- Fetch () can receive cross-domain cookies. You can also set up a cross-domain session using fetch().
- Fetch () does not send cookies. Unless you use the initialization option for credentials.
The Fetch interface
WindowOrWorkerGlobalScope. The fetch () contains the fetch () method, is used to obtain resources Headers is equivalent to request/response Headers, allows you to query to the header information, Request is equivalent to a resource Request. Response is equivalent to a Response to a RequestCopy the code
Fetch mixin
Body provides methods related to the Body in Response/Request that define its content form and how it should be handled.Copy the code
Supported request parameters
// fetch() takes two arguments
// The first argument is: the url is the address of the requested resource
// The second argument is: an init object, optional
Copy the code
The init object represents a configuration object, including all Settings for the request, as follows:
method
: Request method used, such asThe GET, ` ` POST.
headers
: Specifies the request header in the form ofHeaders
Object or containingByteString
Value is an object literal.body
: Requested body information: it may be oneBlob
,BufferSource
(en-US),FormData
,URLSearchParams
orUSVString
Object. Note that requests for the GET or HEAD methods cannot contain body information.mode
: Request mode, such asCors,
No - or cors
Same origin.
credentials
: The credentials of requests, for exampleOmit, same-origin, or omit anything
include
. In order to automatically send cookies within the current domain, this option must be provided, and as of Chrome 50, this property is also acceptableFederatedCredential
(en-US)An instance or an examplePasswordCredential
(en-US)Instance.cache
Request cache mode:default
,no-store
,reload
、no-cache
,force-cache
oronly-if-cached
。redirect
: Available Redirect modes:follow
(Automatic redirection),error
(A redirection will terminate automatically and an error will be thrown), ormanual
(Handle redirection manually). Used by default in ChromeFollow (
The default before Chrome 47 ismanual
).referrer
A:USVString
Can beNo - the referrer, ` ` client
Or a URL. The default isThe client.
referrerPolicy
: specifies the HTTP header referer field. May be one of the following values:No - the referrer,
No - the referrer - the when - downgrade,
The origin,
Origin - the when - cross - origin,
The unsafe - url.
integrity
: including requestedsubresource integrityValue (e.g.Sha256 - BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE =).
Uploading JSON Data
// Use fetch() to POST JSON data
fetch('Fill in the URL', {
method: 'POST'.body: JSON.stringify('Fill in the object here')});Copy the code
Basic use of Fetch
// async and await
async function sendFetch() {
try {
let response = await fetch('http://localhost:5000', {
mode: 'cors'.// Configure cross-domain
});
response.json().then(res= > {
console.log(res); })}catch (err) {
console.log("error:", err);
}
}
sendFetch();
// in this case we need to wrap an async function because we are using await
// If Express is used to simulate back-end data, the configuration is cross-domain as follows:
app.use("/".(req, res, next) = > {
cosnt data = {
/ /... Some of the data
}
* indicates that any domain name is allowed to cross domains
res.header("Access-Control-Allow-Origin"."*");
// The allowed header type
res.header("Access-Control-Allow-Headers"."Content-Type");
// The type of requests that are allowed across domains
res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
/ / send
res.send(data);
});
Copy the code
Fetch some attention points
Fetch (URL, {creadentials: 'include'})
// The server does not reject 400, 500 error codes, and the fetch will only be rejcet if the request cannot be completed due to network errors.
// All versions of IE do not support native Fetch, Fetch - IE8 automatically polyfills with XHR.
// IE8, ie9 XHR does not support CORS cross-domain.
Copy the code