Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created July 18, 2018 20:34
Show Gist options
  • Select an option

  • Save gabemeola/72d278418fd89ff070103ac1cf73aa03 to your computer and use it in GitHub Desktop.

Select an option

Save gabemeola/72d278418fd89ff070103ac1cf73aa03 to your computer and use it in GitHub Desktop.
Fetch for old browsers
/**
* Small request wrapper for XMLHttpRequest
* with an API similar to fetch.
*
* @author Gabe M.
* @param {string} url - Resource Url for Request
* @param {Object} config
* @param {string} [config.method=GET] - REST request method
*/
function request(url, { method = 'GET' } = {}) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.onload = () => {
if (req.status >= 200 && req.status < 300) {
resolve({
status: req.status,
statusText: req.statusText,
text: () => Promise.resolve(req.responseText),
json: () =>
Promise.resolve(req.responseText).then(JSON.parse),
});
} else {
reject(new Error(req.statusText));
}
};
req.onerror = reject;
req.open(method, url, true);
req.send();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment