Introduction to the

  • Fetch () is an updated version of XMLHttpRequest and is used to make HTTP requests inside JavaScript scripts.

usage

  • Fetch () has essentially the same functionality as XMLHttpRequest, with three major differences.
    1. Fetch () uses Promise and does not use callback functions, making it much simpler and more compact to write.
    2. Fetch () has a modular design, with apis scattered over multiple objects (Response, Request, Headers), which makes more sense. In contrast, XMLHttpRequest’s API design is not very good, and the input, output, and state are all managed on the same interface, making it easy to write very messy code.
    3. Fetch () processes data through a Stream object and can be read in chunks, which is helpful for improving website performance and reducing memory footprint. It is useful for scenarios requiring large files or slow network speeds. The XMLHTTPRequest object does not support data streaming. All data must be stored in the cache. It cannot be read in chunks.
  • The basic grammar
    fetch("https://www.baidu.com")
        .then(response= > response.json())
        .then(json= > console.log(json))
        .catch(err= > console.log('Request Failed', err)); 
    Copy the code
    • Response.json () is an asynchronous operation that takes everything and turns it into a JSON object.

The response object

  • Synchronous attributes (attributes retrieved directly from the server)
    • Response.ok: Returns a Boolean value indicating whether the request was successful. True corresponds to the HTTP request status codes 200 to 299. False corresponds to other status codes.
    • Response.status: Returns a number representing the status code of the HTTP response (for example, 200 for a successful request).
    • Response.statusText: Returns a string indicating the status of the HTTP response (for example, the server returns “OK” after a successful request).
    • Response.url: Returns the requested URL. This property returns the final URL if there is a jump to the URL.
    • Response.type: May have the following values
      1. Basic: Common request, that is, same-origin request.
      2. Cors: cross-domain request.
      3. Error: network error, mainly used for Service workers.
      4. Opaque: If the type attribute of the fetch() request is set to no-cors, this value is returned, as described in the Request section. Represents a simple cross-domain request, like a form.
      5. Opaqueredirect: This value is returned if the redirect attribute of the FETCH () request is set to manual, as described in the Request section.
    • Response.redirected: Returns a Boolean value indicating whether the request has been jumped.

Determines whether the request was successful

  • After fetch() sends the request, it is important to note that fetch() will only report an error if the network is wrong or the connection is not available, otherwise the request will be considered successful.
  • That is, fetch() will not fail even if the server returns a status code of 4xx or 5xx (that is, Promise will not change to rejected state).
  • Only through the response. status attribute, the real status code of the HTTP Response can be obtained to determine whether the request is successful.

The Response headers attribute

  • Headers objects can use for… The of loop iterates
  • The Headers object provides the following methods to manipulate Headers.
    • Headers. Get () : Returns the value of the specified key.
    • Headers. Has () : Returns a Boolean value indicating whether a header is included or not.
    • Headers set() : Sets the specified key name to the new key value, or adds it if it does not already exist.
    • Headers. Append () : Adds Headers.
    • Headers. Delete () : Deletes the header.
    • Headers. Keys () : Returns a traverser that traverses all key names in turn.
    • Headers. Values () : Returns a traverser that traverses all key values in turn.
    • Headers. Entries () : Returns a traverser that traverses all key and value pairs ([key, value]) in turn.
    • Headers forEach() : traverses the Headers in turn, executing the argument function once forEach header.

Method of reading content

  • ResponseObject provides different reading methods depending on the type of data returned by the server.
    • Response.text () : Gets the text string.
    • Response.json () : Gets the JSON object.
    • Response.blob () : Gets a binary blob object.
    • Response.formdata () : Gets the formData form object.
    • Response.arraybuffer () : Gets a binary arrayBuffer object.
  • The above five read methods are all asynchronous and return Promise objects. You must wait until the asynchronous operation ends to get the complete data returned by the server.

Response.clone()

  • A Stream object can only be read once, and then it’s gone. This means that only one of the five read methods in the previous section can be used or an error will be reported.
  • Response.text () will finish the Stream. If response.json() is called later, there is no content to read, so an error is reported.

Response.clone(), which can create a copy of the Response object for multiple reads.

Response.body

  • The response object exposes the underlying interface that returns a ReadableStream object for user manipulation. It can be used to read content in chunks. One application is to display the progress of the download.
const response = await fetch('flower.jpg');
const reader = response.body.getReader();
while(true) {
  const {done, value} = await reader.read();
  if (done) {
    break;
  }
  console.log(`Received ${value.length} bytes`)
Copy the code
  • In the example above, the response.body.getreader () method returns a traverser. The iterator’s read() method returns one object at a time representing the block of content that was read. The done attribute of this object is a Boolean value to determine whether it has finished reading or not; The value property is an arrayBuffer array that represents the contents of the content block, while the value.length property is the size of the current block.

Fetch request parameters

  • The first parameter is the URL, and the second parameter can be accepted as a configuration object to customize the HTTP request that is made.

A POST request

const response = await fetch(url, {
  method: 'POST'.headers: {
    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",},body: 'foo=bar&lorem=ipsum'});const json = await response.json();
Copy the code

Submit JSON data

const user =  { name:  'John'.surname:  'Smith'  };
const response = await fetch('/article/fetch/post/user', {
  method: 'POST'.headers: {
   'Content-Type': 'application/json; charset=utf-8'
  }, 
  body: JSON.stringify(user) 
});
Copy the code
  • In the example above, the content-type header is set to ‘application/json; Charset = utf-8 ‘. Because the default is to send plain text, the default value for content-type is ‘text/plain; Charset = utf-8 ‘.

Submit the form

const form = document.querySelector('form');
const response = await fetch('/users', {
  method: 'POST'.body: new FormData(form)
})
Copy the code

File upload

const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
data.append('user'.'foo');

fetch('/avatars', {
  method: 'POST'.body: data
});
Copy the code
  • When uploading a binary file, you do not need to change the content-Type of the header. The browser will set it automatically.

Upload binary data directly

let blob = await new Promise(resolve= >   
  canvasElem.toBlob(resolve,  'image/png'));let response = await fetch('/article/fetch/post/image', {
  method:  'POST'.body: blob
});
Copy the code

Fetch () configures the full API for the object

const response = fetch(url, {
  method: "GET".headers: {
    "Content-Type": "text/plain; charset=UTF-8"
  },
  body: undefined.referrer: "about:client".referrerPolicy: "no-referrer-when-downgrade".mode: "cors".credentials: "same-origin".cache: "default".redirect: "follow".integrity: "".keepalive: false.signal: undefined
});
Copy the code
  • cacheProperty specifies how caching is handled. The possible values are as follows
    • Default: searches the cache for matching requests.
    • No-store: requests the remote server directly and does not update the cache.
    • Reload: Request the remote server directly, and update the cache.
    • No-cache: compares the server resources with the local cache. The server resources are used only when the latest version is available. Otherwise, the cache is used.
    • Force-cache: the remote server is requested only when no cache exists.
    • Only -if-cached: checks only the cache. If it does not exist in the cache, a 504 error is returned.
  • modeProperty specifies the mode of the request. Possible values are as follows:
    • Cors: Default value to allow cross-domain requests.
    • Same-origin: Only same-origin requests are allowed.
    • No-cors: Request methods are limited to GET, POST, and HEAD, and can only use a limited number of simple headers. No complex cross-domain headers can be added, equivalent to the request that can be made by submitting a form.
  • credentialsProperty specifies whether to send cookies. Possible values are as follows:
    • Same-origin: default value. Cookies are sent for same-origin requests but not for cross-domain requests.
    • Include: Sends cookies regardless of same-origin requests or cross-domain requests.
    • Omit: do not omit anything.
  • referrerPolicyProperty to set the rules for the Referer header. Possible values are as follows:
    • No-referreer-when -downgrade: Default, always send the Referer header unless requested HTTP resources from an HTTPS page.
    • No-referrer: No Referer header is sent.
    • Origin: The Referer header contains only the domain name, not the full path.
    • Origin-when -cross-origin: The Referer header for an origin request contains the full path. Cross-domain requests contain only domain names.
    • Same-origin: Cross-domain requests do not send Referer, but same-origin requests are sent.
    • Strict-origin: The Referer header contains only the domain name. HTTPS pages do not send the Referer header when requesting HTTP resources.
    • Strict-origin-when -cross-origin: Indicates that the Referer header contains the complete path in the same-origin request, and only the domain name in the cross-domain request. This header is not sent when HTTPS pages request HTTP resources.
    • Unsafe-url: In any case, the Referer header is always sent.

Cancel the fetch() request

  • After the fetch() request is sent, if you want to cancel it halfway through, you need to use the AbortController object.
let controller = new AbortController();
let signal = controller.signal;
fetch(url, {
  signal: controller.signal
});
signal.addEventListener('abort'.() = > console.log('abort! ')); controller.abort();/ / cancel
console.log(signal.aborted); // true
Copy the code
  • In the example above, we first create an AbortController instance and then send the fetch() request. The signal property of the configuration object must specify that it receives the AbortController instance’s signal, Controller.signal.
  • The Controller.abort () method is used to signal cancellation. Will trigger the abort event at this moment, this event can listen, but can be by the controller. The signal. The aborted attribute to determine whether a cancellation signal has been issued. Here is an example of an automatic cancellation of the request after 1 second.
let controller = new AbortController();
setTimeout(() = > controller.abort(), 1000);
try {
  let response = await fetch('/long-operation', {
    signal: controller.signal
  });
} catch(err) {
  if (err.name == 'AbortError') {
    console.log('Aborted! ');
  } else {
    throwerr; }}Copy the code

Reference article:

Ruan Yifeng blog