“This is the 19th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

introduce

As you know, the Fetch API replaces XMLHttpRequest and provides a better way to access and manipulate HTTP pipes. This installment will take you through how it is used and its pros and cons.

concept

The Fetch API is a JavaScript interface for accessing and manipulating parts of an HTTP pipe. Think of it as an updated version of XMLHttpRequest, which also provides an interface for retrieving resources (including cross-domain requests).

use

Basic usage

fetch(url,{
  method: 'POST'.headers: {
    'Content-Type': 'application/json',},body: JSON.stringify(data),
}).then(res= > {
  return res.json();
}, err= > console.log(err))
.then(data= > {
    console.log(data)
}, err= > console.log(err))
Copy the code

Async&await usage

(async function () {
    try {
        let res = await fetch(url,{
          method: 'POST'.headers: {
            'Content-Type': 'application/json',},body: JSON.stringify(data),
        });
        let data = await res.json();
        console.log(data)
    } catch (err) { }
})()
Copy the code

By using the above two forms, we can use fetch() to convert the requested data to JSON format, but it does more than that. What else can it convert to?

  • .json(): JSON and arrays
  • .arraryBuffer(): binary array
  • .blob(): binary large object (from database, does not need to parse, mostly used in multimedia files)
  • .text()Text:

In addition, there are many ways to play:

Uploading Multiple Files

const formData = new FormData();
const filesInput = document.querySelector('input[type="file"][multiple]');

for (let i = 0; i < filesInput.files.length; ++i) {
  formData.append(`file_${i}`, filesInput.files[i]);
}
fetch(url, {
  method: 'POST'.body: formData,
})
.then(res= > res.json())
.then(res= > {
  console.log('success:', res);
})
.catch(err= > {
  console.error('error:', err);
});
Copy the code

As you can see, FormData still works perfectly with fetch(), and it’s easy to see whether the upload succeeds or fails compared to XMLHttpRequest.

Custom request

/ / set the Headers
const myHeaders = new Headers({
  "Content-Type": "text/plain"}); myHeaders.append("X-Custom-Header"."ProcessThisImmediately")

/ / set the Request
const myRequest = new Request("juejin.png", {
  method: 'GET'.headers: myHeaders,
})

// Send the request
fetch(myRequest)
.then(response= > response.blob())
.then(myBlob= > {
    myImage.src = URL.createObjectURL(myBlob);
});
Copy the code

Fetch () can be used as a combination of Request, Headers, etc. These objects can also be added, deleted, or modified, making them very flexible to use.

advantages

  • fetch()Using the Promise approach instead of the callback function avoids the callback hell problem.
  • fetch()Data is processed through a Stream object, which can be read in chunks. This helps improve site performance and reduce memory footprint, which is useful for scenarios requiring large files or slow network speeds.
  • fetch()Modular design, API scattered over multiple objects (Response object, Request object, Headers object).

disadvantages

Although it optimizes a lot of the behavior and structure of XMLHttpRequest, it is an alternative. However, the problem is still relatively new, there are many compatibility problems, for example, IE series are not compatible with it, some mobile browsers will also report errors.