FetchAPI is more than just a fetch method for making web requests. It provides a generic definition of Request and Response (and other web request-related objects) that replaces the more fragmented definitions of previous web requests. In short, web requests are becoming more standardized.

A simple use case for FetchAPI:

fetch(`url`, {method:'get'.headers: {},body:JSON.stringify({
      name:'Andy'
    })
}).then(response= > {
    return response.json()
}).then(res= > {
    console.log('Result here -->',res)
})
Copy the code

Uncaught SyntaxError: Unexpected end of JSON Input Uncaught SyntaxError: Unexpected end of JSON input Uncaught SyntaxError: Unexpected end of JSON input

Having little personal knowledge or use of FetchAPI, an error like the one above caught my attention and I took some time to look it up and realize its revolutionary significance: standardizing web requests.

FetchAPI makes web requests more formal

First, FetchAPI defines several main interfaces at the language level:

  • RequestRepresents a network request
  • ResponseRepresents data for a network request
  • HeadersDefines a sequence of operations for request headers and response headers

A network request can be represented by the following procedure:

// Create a request request
//1. Construct the request header
const headers = new Headers()
headers.append('content-type'.'application/json')

/ / 2. The construction request
const request = new Request('url', {method:'get'.mode:'cors'.// represents a request for cross-resource sharing
    headers:headers,
    / /...
})
/ / send
fetch(request).then(response= > {
  if(response.ok){
    // An OK response: 200
  }else{
    Other responses: 4xx, 5xx
  }
  const contentType = response.headers.get('content-type')
  .blob(),.text(),.formData()
  if(contentType === 'application/json') {return response.json()
  }else{
      / /...}},err= >{
  // No response was received
  /* 1. The transmission fails due to a network fault
}).then(res= > {
    console.log('Result here -->',res)
})
Copy the code

Above we specify the request-specific module through the constructor:

  • request
  • headers
  • response

Then the Response interface provides the OK Boolean attribute to determine the validity of the Response. In addition, you can specify whether the mode of the request is cross-domain or same-source, specify whether or not credentials are carried, and everything becomes configurable, much more elegant than it is in XMLHttpRequest.

Alternatively, we can construct a custom response:const res = new response ().

All of the apis used above belong to FetchAPI.

How do I handle redirects

As we all know, there is no such thing as redirection in Ajax, because it is an asynchronous update of the document layout and cannot redirect the page to a path like traditional Response.

The front-end can only introduce redirection in Ajax by returning some convention data (usually in httpheaders as markup) from the server, which is read by JS to navigate the page within the client.

FetchAPI takes this into account and normalizes it:

/ / the server.// A controller fragment of the API
res.status(302).redirect('/love').../ / the client
fetch(request).then(response= > {
  // Response.redirected Indicates whether the response is redirected
  const isRedirected = response.redirected
  const redirectedUrl = response.url
  // The client determines whether to jump
})
Copy the code

Here we don’t need any extra data conventions on the front and back end, the specification is much cleaner, isn’t it?

How do I handle timeouts

It is important to note that FetchAPI does not provide a definition of timeout, but rather gives control to the developer, which reduces convenience but improves the robustness of the interface in the long run.

We can handle timeout of fetch requests through the AbortController interface

const abortController = new AbortController()
// Terminate the associated request after 10 seconds (timeout interval is 10 seconds)
setTimeout(() = >{
     abortController.abort()
 },10000)
fetch('/api/login', {
    method: 'get'.signal:abortController.signal
}).then(res= >{},err= >{
  console.log('Here you can catch a timeout error -->',err)
})
Copy the code

conclusion

FetchAPI essentially sums up, summarizes, breaks down, and distills the previously disparate approaches to Ajax into individual modules that complement each other and together support the architecture of web requests. And each module provides many convenient operation methods.

If you haven’t done much with FetchAPI yet, I suggest you try it.