This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021


Writing in the front

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

Browsers provide this object natively


Basic usage

Fetch () has essentially the same functionality as XMLHttpRequest, with three major differences.

(1) Fetch () uses Promise and does not use callback functions, thus greatly simplifying the writing method and making it more concise.

(2) Fetch () adopts modular design, with API scattered on multiple objects (Response object, Request object, Headers object), which is more reasonable; 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 Stream objects and can be read in blocks, which is conducive to improving website performance and reducing memory consumption. It is quite useful for scenarios requiring large files or slow network speed. The XMLHTTPRequest object does not support data streaming. All data must be stored in the cache. It cannot be read in chunks.

In usage, fetch() takes a URL string as an argument, and by default makes a GET request to the URL, returning a Promise object

fetch(url)
  .then(...)
  .catch(...)
Copy the code

Promises can be rewritten with await syntax to make the semantics clearer.

async function getJSON() {
  let url = 'https://github.com';
  try {
    let response = await fetch(url);
    return await response.json();
  } catch (error) {
    console.log('Request Failed', error); }}Copy the code

In the example above, the await statement must be placed in a try… Catch in order to catch errors that may occur during asynchronous operations.


fetch()The second parameter to customize the HTTP request

Fetch () takes the URL as its first argument and can also accept a second argument as a configuration object to customize the HTTP request that is made.

fetch(url, optionObj)
Copy the code

The optionObj of the command above is the second argument.

HTTP request methods, headers, and data bodies are all set in this object

(1) 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

In the example above, the configuration object uses three properties.

  • method: HTTP request method,POST,DELETE,PUTIt’s all in this property setting.
  • headers: an object used to customize the HTTP request header.
  • body: Data body of the POST request.

Note that some headers cannot be set with the HEADERS attribute, such as Content-Length, Cookie, Host, and so on. They are automatically generated by the browser and cannot be modified.

(2) Submit JSON data

const user = { name: 'Liming', age: '15' }; 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 ‘.

(3) Submit the form

const form = document.querySelector('form');

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

(4) File upload

If the form has a file picker, you can write it like in the previous example, where the uploaded file is included in the entire form and submitted together.

Another method is to add files with a script, construct a form, and upload it.

When uploading a binary file, you do not need to change the content-Type of the header. The browser will set it automatically.

(5) Upload binary data directly

Fetch () can also upload binary data directly, placing Blob or arrayBuffer data inside the body property