Learn all about the Fetch API, which is a modern approach to asynchronous network requests using Promises as building blocks
- Introduction to Fetch API
- Use extraction
- Response object
- Request object
- Request header
- POST request
- How to cancel the acquisition request
- Looking for more?
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.
plastic wraphttps://github.com/github/fetchreleasedGitHubAllow us to usefetch
On 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.json
Resources on the same domain.
As you can see,fetch
The function is available worldwidewindow
range.
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 handlerfetch
promiseReplypurpose.
In the next section, we will introduce this object in detail.
Catch the error
sincefetch()
Return promise, we can usecatch
Promise to intercept any errors that occur during the execution of the request, and inthen
Callback:
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
accessheaders
propertyresponse
The 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'))
})
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
statusText
Is 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
url
Represents 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 stringjson()
Returns the body asJSON formatParsed objectblob()
Returns the body asspotpurposeformData()
Return the body as a FormData objectarrayBuffer()
Return the body asArrayBuffer
purpose
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))
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 requestreferrer
: The referral source of the requestcache
: 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, andfetch
Enables 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 laterfetch
After being imported, the request cannot be aborted after opening.
Now, due to the introduction ofAbortController
withAbortSignal
, 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 promiseDOMException
nameAbortError
:
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:
- HTML5 provides some useful tips
- How do I make a CMS-based website work offline
- The complete guide to progressive web applications
- Extract API
- Push API guide
- Channel Messaging API
- Service staff tutorial
- Cache API guide
- Notification API guide
- Dive into IndexedDB
- Selectors API: querySelector and querySelectorAll
- Load JavaScript efficiently with delay and asynchrony
- Document Object Model (DOM)
- Web storage API: local storage and session storage
- Understand how HTTP cookies work
- History API
- WebP image format
- XMLHttpRequest (XHR)
- In-depth SVG tutorial
- What is the data URL
- Roadmap for learning network platforms
- CORS, cross-domain resource sharing
- Network worker
- requestAnimationFrame() guide
- What is Doctype
- Use DevTools console and console API
- Speech Synthesis API
- How to wait for DOM ready event in pure JavaScript
- How to add classes to DOM elements
- How to traverse DOM elements from querySelectorAll
- How to remove classes from DOM elements
- How to check if a DOM element has a class
- How to change the DOM node value
- How to add the click event to the list of DOM elements returned from querySelectorAll
- WebRTC, real-time Web API
- How to get the scroll position of an element in JavaScript
- How to replace DOM elements
- How to only accept images in the input file field
- Why use the preview version of the browser?
- Blob object
- File object
- FileReader object
- FileList object
- ArrayBuffer
- ArrayBufferView
- URL object
- Type array
- DataView object
- BroadcastChannel API
- Streams API
- FormData object
- Navigator object
- How to use the geolocation API
- How to use getUserMedia()
- How to use the drag and drop API
- How to scroll on a web page
- Processing the form in JavaScript
- Keyboard events
- Mouse event
- Touch event
- How to remove all children from DOM element
- How to create HTML attributes using raw Javascript
- How to check if the checkbox is checked using JavaScript?
- How to copy to clipboard using JavaScript
- How to disable buttons using JavaScript
- How to make a page editable in the browser
- How to use URLSearchParams to get query string value in JavaScript
- How to delete all CSS on the page at once
- How to use insertAdjacentHTML
- Safari, warning before exit
- How to add an image to the DOM using JavaScript
- How to reset the table
- How to use Google fonts