Created
February 7, 2016 23:36
-
-
Save thure/e583e68bca08d4ee7f75 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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