What is the Fetch

Fetch, a version of the global object Window, is a more modern alternative to XMLHttpRequest. Fetch does not support abort requests. Fetch is based on promise.

Method of use

Fetch returns a promise and can be used with THEN to process the result, or with async/await. let promise = fetch(url, [options])

Let’s start with the simplest example of get:

// url (required), options (optional)
fetch('https://davidwalsh.name/some/url', {
  method: 'get'
}).then(function(response) {
  // response....
}).catch(function(err) {
  // Error...
});
Copy the code

Here’s a slightly more complex example of how to use POST:

fetch(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
  response.status     //=> number 100-599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  return response.text()
}, function(error) {
  error.message //=> String
})
Copy the code

Fetch uses Promises to handle responses. Fetch takes two arguments:

  • Url: The type is string. This parameter is mandatory
  • Options: The type of object, which is optional, is the requested configuration parameter

You can also initiate a FETCH Request using a Request object instance as an argument:

var request = new Request(url, options);
fetch(request).then(function(response) {
  // handle with response...
}).catch(function(err) {
  // Error...
});
Copy the code

The Options configuration items

Options You can set the following parameters:

  1. Method (String) -Http request method, default: “GET”
  2. Body (String, body types) – HTTP request body, example:
{
  body: new URLSearchParams([['foo', 1], ['bar', 2]]).toString()
}
Copy the code

The types of body include:

Class Default Content-Type
String text/plain; charset=UTF-8
URLSearchParams application/x-www-form-urlencoded; charset=UTF-8
FormData multipart/form-data
Blob inherited from the blob.type property
ArrayBuffer
TypedArray
DataView

Other data structures need to be precoded into one of the above types. For example, json.stringify (data) can be used to serialize a data structure into a JSON string.

  1. Headers (Object, headers) – Request header, default: {}, example:
{
  headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'// Specify form submission})}Copy the code

Headers provides the following methods to add, delete, and check header information:

  • has(name) (boolean)
  • get(name) (String)
  • set(name, value)
  • append(name, value)
  • delete(name)
  • forEach(function(value, name){ … }, [thisContext])
  1. Credentials (String) – The credentials mode for authenticating cross-domain requests. Default: “Omit” — no authentication credentials (such as cookies) in requests “same-origin” — include authentication credentials in requests to the same site “include” — include authentication credentials in requests to all sites

Response Result

Response represents the HTTP Response from the server. Response is taken as an argument to the PROMISE callback. Contains the following attributes:

  • Status (Number) – Indicates the HTTP status code. The value ranges from 100 to 599
  • StatusText (String) – Response text, for example: “Unauthorized”
  • Ok (Boolean) -If status is 2xx, the response is successful. The value is true
  • headers (Headers)
  • url (String)

In addition, Response provides several methods to process the data into a specific data format and return a Promise:

  • Text () – Generates the response text as a string
  • Json () – Generates the result of json.parse (responseText)
  • Blob () – Generates a bloB
  • ArrayBuffer () – Generates an arrayBuffer
  • FormData () – generates formData that can be forwarded to another request

Getting a response usually goes through two phases:

  1. In the first phase, when the server sends a Response header, the Promise uses its built-in Response class to parse the object, checking the HTTP status to determine whether the request was successful or, if the Response body has not yet returned, checking the Response header to determine the status.
  2. In the second stage, in order to get the response body, methods such as text() above need to be called to get the response body in different formats. Note, however, that you can only choose one of the ways to parse the response body. For example, calling response.text() to get a response and then using response.json() will not work because the body content has already been processed. For example, to get an image file:
let response = await fetch('/article/fetch/logo-fetch.svg');
let blob = await response.blob(); // Download as a Blob object
img.src = URL.createObjectURL(blob);
Copy the code

Error handling

If a network error or other reason prevents the HTTP request from completing, the promise of fetch() rejects the error. Note that in the case of HTTP 4XX or 5XX server responses, promises are not rejected. This promise will normally resolve just like HTTP 2xx. We can determine how to handle the error by checking the status code of Response. status:

fetch(...) .then(function(response) {
  if (response.ok) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
})
Copy the code

Compatible with the situation

Up to now, the browser compatibility of FETCH is shown in the figure below: (You can check the browser compatibility at the website can I Use)

If you want to be compatible with IE and older browsers, you can use polyfill: WHATWg-fetch

Renerence

1.github.github.io/fetch/

2. Louiszhai. Making. IO / 2016/11/02 /…

3. Juejin. Im/entry / 68449…

4.davidwalsh.name/fetch