This is the fourth day of my participation in Gwen Challenge

I met the fetch

There are jQ-wrapped Ajax, AXIos, and so on, as well as native XMLHttpRequest when fetching data in the background, but I’m not going to cover that today, I’m going to cover another API, FETCH.

Fetch, in plain English, is an alternative to XMLHttpRequest. If someone asks you, besides XMLHttpRequest getting background data, are there any alternatives to native apis?

This is where you can answer, and there is a solution called fetch.

The fetch usage

Fetch is available in modern browsers, has been mounted to the BOM, and can be used directly on the Google console. Fetch returns a Promise to check the support for FETCH: The support for Fetch

Of course, if fetch is not supported, it is fine to use a third-party ployfill: fetch-ployfill

Simple to use

// Fetch
// 
fetch('https://www.xxx.com/search') // Return a Promise object
  .then((res) = > {
    console.log(res.text())  // res.text() is the promise object
  }).then((res) = > {
    console.log(res)
  })
Copy the code

fetch API

fetch(url[, option])

  • url:

This parameter is mandatory. Defines the resource to be obtained. This could be: a URL string containing the URL of the resource to fetch a Request object

  • option

An optional configuration item object that includes all Settings for the request. The optional parameters are:

Method: Indicates the request method, such as GET and POST. Headers: Indicates the headers of the request. Object of the form Headers. Body: The requested body information: could be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that requests for the GET or HEAD methods cannot contain body information. Mode: indicates the request mode, such as CORS, no-cors, or same-origin. Credentials: Required credentials, such as omit, same-origin, or include. To automatically send cookies within the current domain, you must provide this option, cache: request cache mode: Default, no-store, reload, no-cache, * force-cache, or only-if-cached. Redirect: Available redirect modes: Follow (automatic redirection), ERROR (automatically terminating and throwing an error if a redirect occurs), or manual (handling redirection manually). In Chrome, the default before Chrome 47 is follow, and starting with Chrome 47 is manual. .

example

Get requests are carried directly in urls similar to

// Fetch
fetch('https://www.xxx.com/search/?a=1&b=2', { // Write the passed parameters in the URL
    method: 'GET'
  })
  .then((res) = >{
    return res.text()
  })
  .then((res) = >{
    console.log(res)
  })
Copy the code

The POST request is set in option.body, like this

/ / the first
var url = 'https://xxxx.com/profile';
var data = {username: 'xxx'};

fetch(url, {
  method: 'POST'.// or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res= > res.json())
.catch(error= > console.error('Error:', error))
.then(response= > console.log('Success:', response))


/ / the second
fetch('https://www.xxx.com/search', {
    method: 'POST'.body: new URLSearchParams([["foo".1], ["bar".2]]).toString() // Here is the request object
  })
  .then((res) = >{
    return res.text()
  })
  .then((res) = >{
    console.log(res)
  })
Copy the code

conclusion

Fetch itself returns a promise, combined with async and await, which is quite comfortable to use. You can experience it with fair treatment.