Skip to content

Instantly share code, notes, and snippets.

@crivotz
Created January 8, 2019 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crivotz/ef646521596befdfc8d8d68b8bc632e9 to your computer and use it in GitHub Desktop.
Save crivotz/ef646521596befdfc8d8d68b8bc632e9 to your computer and use it in GitHub Desktop.
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