Created
January 8, 2019 15:00
-
-
Save crivotz/ef646521596befdfc8d8d68b8bc632e9 to your computer and use it in GitHub Desktop.
Request with XMLHttpRequest and promises
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
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