Extract API

Learn all about the Fetch API, which is a modern approach to asynchronous network requests using Promises as building blocks

Introduction to Fetch API

Since IE5 was released in 1998, we can choose to use the following commands to make asynchronous network calls in the browserXMLHttpRequest(XHR).

In the years that followed, GMail and other rich applications used it extensively, and made the method so popular that it must have a name:AJAX.

It has always been painful to use XMLHttpRequest directly, and it is almost always abstracted by some libraries, especially jQuery has built its own helper function around it:

  • jQuery.ajax()
  • jQuery.get()
  • jQuery.post()

and many more.

They have had a huge impact on making it more accessible, especially in ensuring that all functions work properly on older browsers.

ThisExtract API, Has been standardized as a modern method for asynchronous network requests and usecommitted toAs a building block.

Except IE, Fetch has good support on all major browsers.

The browser support for the Fetch API

plastic wraphttps://github.com/github/fetchreleasedGitHubAllow us to usefetchOn any browser.

Use extraction

It is very simple to start using Fetch for GET requests:

fetch('/file.json')

And you are already using it: fetch will make an HTTP request to getfile.jsonResources on the same domain.

As you can see,fetchThe function is available worldwidewindowrange.

Now, to make it more useful, let's actually see what the contents of the file are:

fetch('./file.json')
  .then(response => response.json())
  .then(data => console.log(data))

callfetch()Return acommitted to. Then, we can pass athen()The method of commitment.

The return value received by the handlerfetchpromiseReplypurpose.

In the next section, we will introduce this object in detail.

Catch the error

sincefetch()Return promise, we can usecatchPromise to intercept any errors that occur during the execution of the request, and inthenCallback:

fetch('./file.json')
.then(response => {
  //...
})
.catch(err => console.error(err))

Another way to catch errors is to manage them in the first placethen:

fetch('./file.json')
.then(response => {
  if (!response.ok) { throw Error(response.statusText) }
  return response
})
.then(response => {
  //...
})

Response object

The response object returned by afetch()The call contains all the information about the request and the network request response.

Metadata

Header

accessheaderspropertyresponseThe object enables you to view the HTTP headers returned by the request:

fetch('./file.json').then(response => {
  console.log(response.headers.get('Content-Type'))
  console.log(response.headers.get('Date'))
})

Request headers for fetch

status

This attribute is an integer representing the status of the HTTP response.

  • 101, 204, 205, or 304 are empty body states
  • 200 to 299 (inclusive) is OK (successful)
  • 301, 302, 303, 307, or 308 are redirects

    fetch('./file.json').then(response => console.log(response.status))
    

statusText

statusTextIs the attribute that represents the response status message. If the request is successful, the status isOK.

fetch('./file.json').then(response => console.log(response.statusText))

URL

urlRepresents the full URL of the attribute we extracted.

fetch('./file.json').then(response => console.log(response.url))

Body content

The response has a body, which can be accessed in several ways:

  • text()Return the body as a string
  • json()Returns the body asJSON formatParsed object
  • blob()Returns the body asspotpurpose
  • formData()Return the body as a FormData object
  • arrayBuffer()Return the body asArrayBufferpurpose

All these methods return a promise. example:

fetch('./file.json')
  .then(response => response.text())
  .then(body => console.log(body))
fetch('./file.json')
  .then(response => response.json())
  .then(body => console.log(body))

Get JSON

can useES2017 Asynchronous function:

;(async () => {
  const response = await fetch('./file.json')
  const data = await response.json()
  console.log(data)
})()

Request object

The Request object represents a resource request, usually usednew Request()API.

example:

const req = new Request('/api/todos')

The Request object provides several read-only attributes to check the detailed information of the resource request, including

  • method: Request method (GET, POST, etc.)
  • url: The requested URL.
  • headers: The associated Headers object of the request
  • referrer: The referral source of the request
  • cache: The requested cache mode (for example, default, reload, no cache).

And disclosed several methods, includingjson(),text()withformData()The subject of the processing request.

The complete API can be found at the following locationhttps://developer.mozilla.org/docs/Web/API/Request

Request header

Being able to set HTTP request headers is crucial, andfetchEnables us to use the Headers object to do this:

const headers = new Headers()
headers.append('Content-Type', 'application/json')

or:

const headers = new Headers({
  'Content-Type': 'application/json'
})

To attach the header to the request, we use the Request object and pass it tofetch()Instead of passing the URL.

instead:

fetch('./file.json')

We are indeed

const request = new Request('./file.json', {
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
fetch(request)

The Headers object is not limited to setting values, we can also query it:

headers.has('Content-Type')
headers.get('Content-Type')

We can delete the previously set header:

headers.delete('X-My-Custom-Header')

POST request

Extraction also allows any other HTTP methods to be used in your request: POST, PUT, DELETE or OPTIONS.

Specify the method in the method attribute of the request, and pass other parameters in the header and request body:

Example of POST request:

const options = {
  method: 'post',
  headers: {
    'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  body: 'name=Flavio&test=1'
}

fetch(url, options).catch(err => { console.error(‘Request failed’, err) })

How to cancel the acquisition request

A few years laterfetchAfter being imported, the request cannot be aborted after opening.

Now, due to the introduction ofAbortControllerwithAbortSignal, The general API for notificationsSuspendMemorabilia

You can integrate this API by passing signals as fetch parameters:

const controller = new AbortController()
const signal = controller.signal

fetch(’./file.json’, { signal })

You can set a timeout to trigger an abort event 5 seconds after the start of the get request to cancel it:

setTimeout(() => controller.abort(), 5 * 1000)

Conveniently, if the extraction operation has returned, callabort()Will not cause any errors.

When an abort signal occurs, the withdrawal will use the following command to reject the promiseDOMExceptionnameAbortError:

fetch('./file.json', { signal })
  .then(response => response.text())
  .then(text => console.log(text))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.error('Fetch aborted')
    } else {
      console.error('Another error', err)
    }
  })

Looking for more?

It’s hard to use the Internet, right? You may findAxiosThe JavaScript library may build some additional functions based on Fetch, which are more suitable for your needs. check it out!

Download mine for freeJavaScript beginner's manual


More browser tutorials: