Introduction to the

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global FETCH () method, which provides a simple, logical way to fetch resources asynchronously across a network.

Fetch () must take one argument, a path. Whether the request succeeds or fails, it returns a Promise object, resolve corresponding to the Response of the request. You can also set a second (optional) parameter, options (commonly used as follows, see Request for details).

configuration

options={
    // Request mode GET,POST, etc
    method: "GET".// Request headers
    headers: {
        Accept: 'application/json, text/plain, */*'.'Content-Type': 'application/json; charset=UTF-8'.'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',},// omit: never send cookies.
    // same-origin Cookies are sent only if the URL has the same origin as the response script
    // include always sends local cookies validation information for the request resource domain
    credentials: 'include'.// Contain the mode for the request (for example, cors, no-cors, same-origin, navigate)
    // no-CORS: applies to cross-domain requests without CORS response headers
    // CORS indicates that the same-domain and cross-domain requestable success with the CORS response header is successful. Other requests will be rejected
    mode: 'cors'.// Contains the requested cache mode (e.g., default, reload, no-cache). See the following for specific parameters (cache parameters)
    cache: 'default'
}
Copy the code
Cache parameters

Cache indicates how to handle the cache. It complies with the HTTP specification and has the following values:

  1. Default: The browser searches the HTTP cache for a matching request.
  2. No-store: The browser retrieves resources from a remote server without first looking at the cache and does not update the cache with the downloaded resources
  3. Reload: The HTTP cache is ignored before the request, but when the request gets the response, it actively updates the HTTP cache.
  4. No-cache: If there is a cache, the fetch will send a conditional query request and a normal request, and when it gets the response, it will update the HTTP cache.
  5. Force-cache: The browser looks for a matching request in its HTTP cache.
    • If there is a match,Fresh or out of dateIs returned from the cache.
    • If there is no match, the browser makes a normal request and updates the cache with the downloaded resources
  6. Only -if-cached: fetch from cache, even if the cache expires. If there is no cache, the browser will return an error

case

This is a relatively basic case, and the catch problem is not dealt with in order to make it clear.

var url = 'https://zhidao.baidu.com/question/api/hotword?pn=1561&rn=5&t=1551165472017';
fetch(url).then(function(response) {
  return response;
}).then(function(data) {
  console.log(data);
})
Copy the code

You can paste this code directly into the console yourself, but to prevent same-origin policies and see more detailed data it is best to enter it in the console at https://zhidao.baidu.com. If we were on another page we would add {mode: “no-cors”} to the second parameter of the fetch method. In order to see more clearly, I have posted the print results of both cases, as shown below:

Enter the address at the https://zhidao.baidu.com web console

An address entered in another web console

We will find that the two printing results are basically different. First, many data in the cross-domain printing results are empty. In addition, we also find that the types are different.

The response type of the fetch request (response.type) is one of the following:

  • Basic: in the same domain, the response type is Basic.
  • Cors: across domains, the cORS response header is returned. The response type is CORS.
  • Opaque: In cross-domain mode, the server does not return the CORS response header. The response type is Opaque.

Fetch set {mode=’no-cors’}

If you look at this, you’ll notice that we still haven’t got the data, we’ve just got a Response object. So how do you get the data?

Look good:

var url = 'https://zhidao.baidu.com/question/api/hotword?pn=1561&rn=5&t=1551165472017';
fetch(url).then(function(response) {
  // Get the data through json method on the response prototype and return it
  return response.json();
}).then(function(data) {
  // Print the received data
  console.log(data);
})
Copy the code

Get the data through json method on response prototype and return it. The response prototype is printed as follows:

Response. json/response.text can only be used once, and both methods can be used simultaneously or twice.

Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream is locked

Why not use it twice?

The data flow can be read only once. Once the data flow is read, an error will be reported when the data flow is read again. You can make a copy using Response.clone ().

Why can only read once?

The answer is still in search, but also hope to know readers can point out.

(async/await) {async/await = async/await = async/await = async/await = async/await

var url = 'https://zhidao.baidu.com/question/api/hotword?pn=1&rn=5&t=1551191647420';
let getData = async() = > {let response = await fetch(url);
    let data = response.json();
    console.log(data)
}
Copy the code

Print data as follows:

As data is a Promise object, its internal variable [[PromiseValue]] is not available externally, but can only be obtained in THEN, so then is added to obtain data

let response = await fetch(url);
let data = response.json();
data.then((res) = >{
  console.log(res)
})
// Get the res
Copy the code

encapsulation

We use fetch to make a simple request package. By the way, we review options again. Many configurations may not be needed in practice, and there are default configurations (default configurations of Options are in parentheses below).

function request(url, data = {}) {
  // The default options for the options configuration are in parentheses
    return fetch(url, {
        method: "POST".//(GET), POST, PUT, DELETE, etc
        mode: "cors".// (same-origin), no-cors, cors
        cache: "no-cache".// (default), no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin".//(same-origin), include, omit
        headers: {
            "Content-Type": "application/json".// "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow".//(follow), manual, error
        referrer: "no-referrer".//(client), no-referrer
        body: JSON.stringify(data), // The format should be synchronized with "content-type"
    })
    .then(response= > response.json());
}
Copy the code

The last

Write a post for the first time, if there are mistakes or not rigorous place, please be sure to give correction, thank you

Reference:

  • Fetch API
  • Traditional Ajax is dead, Fetch lives forever