open core »

Simple XMLHttpRequest with Fetch

This week, the new Fetch standard has landed in Chrome Canary (version 42). This is one of the specs I’ve been waiting for. It really simplifies XMLHttpRequests with a cleaner interface, and comes with built-in promises.

So to give you some perspective, here’s how you currently do an XMLHttpRequest:

var req = new XMLHttpRequest();

req.onload = function () {
    console.log(this.responseText);
};

req.open('GET', 'http://someendpoint.com/api/stuff', true);
req.send();

This is a very simple example, and as you know, it can get much more verbose if you start handling error cases.

And now, this is the same request made with window.fetch() but with bonus error handling:

window.fetch('http://someendpoint.com/api/stuff').then(function (response) {
    return reponse.text();
}).then(function (text) {
    console.log(text);
}).catch(function (e) {
    console.log(e);
});

In my opinion this is much simpler. And it’s also customizable:

window.fetch('http://someendpoint.com/api/stuff', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ someField: 1234, anotherField: 'foobar' })
}).then(function (response) {
    return reponse.text();
}).then(function (text) {
    console.log(text);
}).catch(function (e) {
    console.log(e);
});

Have a look at the spec, there are much more features included.

What about other browsers support?

Github has released a Fetch polyfill that works perfectly well with all browsers (IE 9+ included), just make sure you also install es6-promise polyfill for promise support in older browsers.