Fetch API

The Fetch API utilizes the fetch method for fetching resources. In the past this was achieved with XMLHttpRequest. Not only is fetch simpler to use, it also provides lower level access to requests and responses.

In the Microsoft Edge Developer blog post, Fetch (or the undeniable limitations of XHR), the following code snippets compare XHR to Fetch when making a request for a JSON resource:

XHR

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';

xhr.onload = function() {
   console.log(xhr.response);
};

xhr.onerror = function() {
   console.log("Houston, we've got a problem.");
};

xhr.send();

Fetch

fetch(url).then(function(response) {
   return response.json();
}).then(function(jsonData) {
   console.log(jsonData);
}).catch(function() {
   console.log("Houston, we've got a problem.");
});

Headers

The Headers object is used to perform actions on request and response headers. Within a Headers object is a list of associated headers.

The Headers object has the following methods:

Method Description
append Appends a new value to an already existing header inside a Headers object.
delete Deletes a header from the current Headers object.
get Gets the first value of a header from the current Headers object.
has Checks whether or not a header exists within the current Headers object.
set Sets a new value to an already existing header inside a Headers object.

Request and Response

The Fetch API gives you more freedom when it comes to making requests and responses when compared to XHR. The Request object represents a resource request, while the Response object represents the response of a request. The body of a Response object contains a stream that is read from using the Streams API.

Both the Response and Request objects have the same methods:

Method Description
arrayBuffer Takes a Response or Request stream and returns a promise for an ArrayBuffer object.
blob Takes a Response or Request stream and returns a promise for a Blob object.
json Takes a Response or Request stream and returns a promise for an object containing JSON data.
text Takes a Response or Request stream and returns a promise for a USVString object.

Both objects also have respective clone methods:

Method Description
clone Creates a copy of the current Response object.
clone Creates a copy of the current Request object.

API reference

Fetch

Fetch (or the undeniable limitations of XHR)

Streams API

XMLHttpRequest

Specification

Fetch