Skip to content

Instantly share code, notes, and snippets.

@aliams

aliams/fetch.js Secret

Last active September 27, 2018 03:22
Show Gist options
  • Save aliams/2b51762b48a8673599823135cc604f74 to your computer and use it in GitHub Desktop.
Save aliams/2b51762b48a8673599823135cc604f74 to your computer and use it in GitHub Desktop.
Simple fetch vs. XHR example
fetch('weather.json')
.then(function(response) {
if (response.headers.get('content-type').includes('json')) {
return response.json();
} else {
throw new TypeError();
}
})
.then(processJSON);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'weather.json');
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status == 200
&& xhr.getResponseHeader('Content-Type').indexOf('json') !== -1) {
processJSON(xhr.response);
} else {
throw new TypeError();
}
}
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment