Skip to content

Instantly share code, notes, and snippets.

@thure
Created February 7, 2016 23:36
Show Gist options
  • Save thure/e583e68bca08d4ee7f75 to your computer and use it in GitHub Desktop.
Save thure/e583e68bca08d4ee7f75 to your computer and use it in GitHub Desktop.
module.exports = function (options) {
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
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) {
reject(new Error('Server responded with a status of ' + req.status));
} else {
options.expect = options.expect || 'anything';
switch (options.expect.toLowerCase()) {
case 'json':
resolve(JSON.parse(e.target.responseText));
break;
case 'xml':
resolve(e.target.responseXML);
break;
default:
resolve(e.target.responseText);
break;
}
}
};
req.send(options.data || void 0);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment