Last active
August 29, 2015 14:13
-
-
Save nhusher/1d868177b20beef95117 to your computer and use it in GitHub Desktop.
A tiny promise-based XHR function. Useful for debugging in the console.
This file contains hidden or 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 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 {}; | |
}) | |
} |
This file contains hidden or 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 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