(Add star to front end to improve front end skills)
English: Flavio translation: Translation/Angle
https://zcfy.cc/article/understanding-the-fetch-api
Introduce the Fetch API
Since the release of Internet Explorer 5 in 1998, asynchronous web requests in browsers have been made using XMLHttpRequest (XHR).
Over the next few years, Gmail and other applications used this method extensively, making it popular and giving it a name: AJAX.
Using XMLHttpRequest directly is always a pain, and many libraries encapsulate this method. In particular, jQuery encapsulates this method as follows:
-
jQuery.ajax()
-
jQuery.get()
-
jQuery.post()
There is a lot of compatibility work done internally to make these methods work on older browsers.
The Fetch API, already the standard method for asynchronous network requests in modern browsers, uses Promise as a basic building block.
Fetch is well supported in all major browsers except IE.
Lot has released polyfill on https://github.com/github/fetch, making the fetch can be used in any browser.
Using the Fetch
Using Fetch in a GET request is very simple, as follows:
fetch('/file.json')
Copy the code
The above code shows that fetch creates an HTTP request for a file. Json resource in the local domain.
As you can see, the FETCH function can be used in the global Window scope.
Now, to do something more useful, take a look at the contents of the requested file:
fetch('./file.json')
.then(response => response.json())
.then(data => console.log(data))
Copy the code
Fetch () returns a promise. We then write handlers using the then() method to handle the results returned asynchronously in the Promise.
The handler receives the return value of the Fetch Promise, which is a Response object.
We’ll see the details of this object in the next section.
Capture the error
Since fetch() returns a promise, we can use the promise’s catch to intercept any errors that occur in the callback function in the execution of the request and then.
fetch('./file.json')
.then(response => {
/ /...
})
.catch(err => console.error(err))
Copy the code
The response object
The response object returned by calling fetch() contains all the request and response information about the network request.
metadata
headers
HTTP request headers can be accessed by accessing the HEADERS property of the response object as follows:
fetch('./file.json').then(response => {
console.log(response.headers.get('Content-Type'))
console.log(response.headers.get('Date'))
})
Copy the code
status
This property is an integer representing the HTTP response status.
-
101, 204, 205, or 304 represent states with no response body
-
200 to 299 indicates that the request is successful
-
301, 302, 303, 307, or 308 represent the status of the redirect
fetch('./file.json').then(response => console.log(response.status))
Copy the code
statusText
The statusText attribute represents response status information. If the request succeeds, the value is “OK”.
fetch('./file.json').then(response => console.log(response.statusText))
Copy the code
url
Url represents the full path URL of the resource we requested.
fetch('./file.json').then(response => console.log(response.url))
Copy the code
Response body
The response will have a response body, which can be retrieved through the text() or JSON () methods, which will return a Promise object.
fetch('./file.json')
.then(response => response.text())
.then(body => console.log(body))
Copy the code
fetch('./file.json')
.then(response => response.json())
.then(body => console.log(body))
Copy the code
The same function can be used with the ES2017 async function:
; (async () => {
const response = await fetch('./file.json')
const data = await response.json()
console.log(data)
}) ()
Copy the code
The request object
A Request object represents a Request for a resource, which is typically created through the New Request() API.
Such as:
const req = new Request('/api/todos')
Copy the code
The request object provides several read-only properties to check the details of the resource request, including
-
Method: Request methods (GET, POST, etc.)
-
Url: The requested URL
-
Headers: The header information object of the request
-
Referrer: The source of the requested site
-
Cache: Requested cache mode (for example, default, reload, no-cache).
Methods such as JSON (), text(), and formData() are provided to handle the request body.
All of the API can check https://developer.mozilla.org/docs/Web/API/Request
Request header
Setting the HTTP request header is a basic function. Fetch uses the Headers object to allow us to manipulate the request header:
const headers = new Headers()
headers.append('Content-Type', 'application/json')
Copy the code
Or even simpler:
const headers = new Headers({
'Content-Type': 'application/json'
})
Copy the code
To add headers to the Request, we use the Request object and add it to the fetch() argument instead of passing the URL argument.
Instead of the following code:
fetch('./file.json')
Copy the code
Let’s do this
const request = new Request('./file.json', {
headers: new Headers({
'Content-Type': 'application/json'
})
})
fetch(request)
Copy the code
The Headers object is not restricted to setting a value, we can also query it:
headers.has('Content-Type')
headers.get('Content-Type')
Copy the code
And we can delete the headers we set earlier:
headers.delete('X-My-Custom-Header')
Copy the code
A POST request
Fetch can also use other HTTP methods, such as POST, PUT, DELETE, or OPTIONS.
Specifying the method of the request in the method attribute adds additional parameters to the request header and body:
Here is an example of a POST request:
const options = {
method: 'post',
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: 'foo=bar&test=1'
}
fetch(url, options).catch(err => {
console.error('Request failed', err)
})
Copy the code
The Fetch disadvantages
While FETCH is a huge improvement over XHR, especially its integration into the Service Worker, FETCH does not yet have a method to abort a request. And Fetch cannot monitor upload progress.
If you need these features in your application, the Axios library can be a good choice.
How do I cancel the FETCH request
In the early years of fetch, there was no way to cancel a request that had already been made.
Now we can do this, thanks to AbortController and AbortSignal, which are generic APIS for notifying abort events.
You can integrate these apis by adding a signal parameter:
const controller = new AbortController()
const signal = controller.signal
fetch('./file.json', { signal })
Copy the code
You can set a timeout to cancel the request 5 seconds after it was sent:
setTimeout(() => controller.abort(), 5 * 1000)
Copy the code
Conveniently, calling abort() does not cause an error if fetch has already returned.
When the cancellation signal occurs, the fetch throws a DOMException with a name attribute value of “AbortError”, which can be caught in the Promise’s catch:
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)
}
})
Copy the code
Recommended reading
(Click on the title to jump to read)
The Fetch API is easy to understand
Front-end giants (1) : execution context vs. execution stack, variable objects
Three new JavaScript features to look forward to!
Find this article helpful? Please share it with more people
Pay attention to “front-end daqo” plus star label, improve front-end skills
If you like, click “good-looking” bai ~