Skip to content

Instantly share code, notes, and snippets.

@ArEnSc
Created May 7, 2016 23:15
Show Gist options
  • Save ArEnSc/a40cf3767b7f6393e645cb4d65a61d85 to your computer and use it in GitHub Desktop.
Save ArEnSc/a40cf3767b7f6393e645cb4d65a61d85 to your computer and use it in GitHub Desktop.
Better way to code your requests simar
/**
optz
{
method: String,
url: String,
params: String | Object,
headers: Object
}
**/
const request = (opts) => {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(opts.method, opts.url);
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]);
});
}
let params = opts.params;
// 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('&');
}
xhr.send(params);
});
}
request({
method:'GET',
url: 'https://mealacct.mcmaster.ca/OneWeb/Account/LogOn',
}).then((data) => {
console.log(data)
}).catch((error) => {
console.log(error)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment