Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Request with XMLHttpRequest and promises
function makeRequest(opts) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(opts.method, opts.url);
xhr.withCredentials = true;
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText,
});
};
if (opts.headers) {
Object.keys(opts.headers).forEach(function(key) {
xhr.setRequestHeader(key, opts.headers[key]);
});
}
var params = opts.params;
var formdata = opts.formdata;
// We'll need to stringify if we've been given an object
// If we have a string, this is skipped.
if (params && typeof params === 'object') {
params = Object.keys(params)
.map(function(key) {
return (
encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
);
})
.join('&');
}
if (params) var data = params;
else if (formdata) var data = JSON.stringify(formdata);
else var data = null;
xhr.send(data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment