Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Last active August 8, 2018 14:59
Show Gist options
  • Save amitasaurus/e23e717e206e5de35bab401206f77830 to your computer and use it in GitHub Desktop.
Save amitasaurus/e23e717e206e5de35bab401206f77830 to your computer and use it in GitHub Desktop.
Promise based XHR Wrapper
let _Http = obj => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(obj.method || "GET", obj.url);
if (obj.headers) {
Object.keys(obj.headers).forEach(key => {
xhr.setRequestHeader(key, obj.headers[key]);
});
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send(JSON.stringify(obj.body));
});
};
//Guildelines to use
/*
_http({
method: 'POST', //GET by default
url: 'data.json',
body: JSON.stringify(payload)
headers: {
'my-custom-header': 'value'
}
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment