Introduction to the Fetch API
XMLHttpRequest has been the browser standard for a long time for JSON and XML requests. For most of us in web development we are quite familiar with AJAX abstractions such as jQerry's $ajax
or Angular's $q
This is because for a long time browser support for XMLHttpRequest was spotty at best.
Browsers have greatly improved over the past couple of years but we continue to use abstractions because of XMLHttpRequest's clunky and ugly API. Here is a simple example.
var xhrReq = new XMLHttpRequest();
xhrReq.open('GET', '/url/api');
xhrReq.responseType = 'json';
xhrReq.onload = function() {
console.log(xhr.response);
};
xhrReq.onerror = function(error) {};
xhrReq.send();
Pretty ugly syntax. It's not using promises to handle the response which makes complex asynchronous code a real pain.
The Fetch API
Lets look at the new Fetch API to get some JSON.
fetch('/url/api')
.then(function(response) {
console.log(response.json());
})
.catch(function(error) {});
In its simplest form thats it! Much cleaner syntax and uses modern ES6 JavaScript promises. We can chain on our promise to modify our response or to handle some other work before we hand it back.
fetch('/url/api')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {});
Fetch by default uses GET. If you need to POST some JSON to the server you can use something like the following.
fetch('/url/api', {
method: 'post',
body: JSON.stringify({
email: document.querySelector('#emailInput'),
name: document.querySelector('#nameInput')
})
}).then(function(response) {
/* ... */
});
If you need to set response headers for authentication like many API's require you can do something like the following.
fetch('/url/api', {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Auth: 'authkey'
}
}).then(function(response) {
/* ... */
});
Fetch is in active development with features being added to it currently. You can start using it today in Chrome and use a polyfill for all other browsers with ie9+ support. To get a in depth understanding of the new Fetch API I suggest looking into the HTML5 Rocks article. Fetch will replace the XMLHttpRequest API and can't come soon enough.