Last Updated: September 09, 2019
·
873
· dimitative

Simple HTTP request as Promise

function http(options) {
    var deferred = q.defer(),
    req = new XMLHttpRequest();

if (!options.url) {
    throw new Error('No url given');
} else {
    req.open(options.method || 'GET', options.url, true);
}

// Set request headers if provided
Object.keys(options.headers || {}).forEach(function (key) {
    req.setRequestHeader(key, options.headers[key]);
});

req.onreadystatechange = function (e) {
    if (req.readyState !== 4) { return; }

    if ([200, 304].indexOf(req.status) === -1) {
        deferred.reject(new Error('Server responded with a status of ' + req.status));
    } else {
        deferred.resolve(e.target.response);
    }
};

req.send(options.data || void 0);

return deferred.promise;

}

With friendly support from Matthew Phillips:
https://gist.github.com/matthewp/3099268