Skip to content

Instantly share code, notes, and snippets.

@ArEnSc
Created May 11, 2016 01:22
Show Gist options
  • Save ArEnSc/615cac2d4d3fcb1ee3ea5d7a9e8dabd9 to your computer and use it in GitHub Desktop.
Save ArEnSc/615cac2d4d3fcb1ee3ea5d7a9e8dabd9 to your computer and use it in GitHub Desktop.
request = (opts) => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
let params = opts.params;
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: xhr.status,
statusText: xhr.statusText
});
};
if (opts.headers) {
Object.keys(opts.headers).forEach(function (key) {
xhr.setRequestHeader(key, opts.headers[key]);
});
}
if (opts.method === 'GET' && params && typeof params === 'object') {
params = Object.keys(params).map(function (key) {
return encodeURIComponent(key).replace(/%20/g, '+') + '=' + encodeURIComponent(params[key]).replace(/%20/g, '+');
}).join('&');
xhr.open(opts.method, opts.url + '?' + params);
xhr.send()
} else {
xhr.open(opts.method, opts.url);
if (params && typeof params === 'object') {
params = Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
xhr.send(params);
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment