Skip to content

Instantly share code, notes, and snippets.

@nhusher
Last active August 29, 2015 14:13
Show Gist options
  • Save nhusher/1d868177b20beef95117 to your computer and use it in GitHub Desktop.
Save nhusher/1d868177b20beef95117 to your computer and use it in GitHub Desktop.
A tiny promise-based XHR function. Useful for debugging in the console.
function json(u, t) {
return xhr(u, t || 'GET', {
Accept: 'application/json',
Authorization: 'Bearer ' + localStorage.token
}).then(function(v) {
return JSON.parse(v.responseText);
}, function(e) {
console.error(e);
return {};
})
}
function xhr(u, t, headers) {
return new Promise(function(r) {
var x = new XMLHttpRequest();
x.onload = function() { r(x); };
x.open(t || 'GET', u, true);
if(headers) {
Object.keys(headers).forEach(function(k) {
x.setRequestHeader(k, headers[k]);
});
}
x.send();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment