The fetch interpretation

The FETCH API provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple and reasonable way to fetch resources asynchronously across the network. This functionality was previously implemented using XMLHttpRequest. Fetch provides a more ideal alternative that can easily be used by other technologies, such as Service Workers.

[Problem] Cross-domain and carrying Cookies in FETCH requests

In some requests, you will encounter APIs that want to access different sources via the request and want to carry cookies.

Solve cross-domain problems

FETCH can set different modes to make the request valid. The pattern can be defined in the second parameter object of the FETCH method.

fetch(url, {mode: 'cors'});

Schemas can be defined as follows:

  • Same-origin: Indicates that the same source can be accessed, whereas the browser rejects it
  • CORS: Indicates that cross-domain applications with the same origin and CORS response header can be successfully requested and others rejected
  • Cors-with-Force-Preflight: Indicates that a Preflight check will be performed before the request is sent.
  • NO-CORS: indicating that the cross-domain request does not have a CORS response header scenario where the corresponding type is opaque, but we almost never see anything of value out of the return type that we opaque, such as response, status, or URL.

Resolves the issue of carrying cookies across domains

When cookies are required in a cross-domain request, add the Credentials attribute to the second parameter object of the FETCH method and set the value to “include”.

fetch(url,{
  credentials: 'include'
});

In addition, the credentials can take the following values:

  • Omit: Default value, which is the default value.
  • Same -origin: Same -origin: Cookies are sent only on same-domain requests.

But at the same time, if the target server can accept and accept cookies sent across domains, The Credentials Credentials response header is set to “true”. The Credentials Credentials Credentials can be used in the Credentials Credentials response. The Credentials Credentials Credentials can be set to “true”. Cookies can be allowed for cross-domain requests.

Welcome to my personal blog
ximikang.icu