Skip to content

Instantly share code, notes, and snippets.

@dbarjs
Created April 27, 2016 15:01
Show Gist options
  • Save dbarjs/78c56655207f8ba370191a955a987051 to your computer and use it in GitHub Desktop.
Save dbarjs/78c56655207f8ba370191a955a987051 to your computer and use it in GitHub Desktop.
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
xhr.setRequestHeader('Accept', 'application/json; charset=utf-8');
// xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'https://api.instagram.com/v1/users/225309780/media/recent/?client_id=80703e5f430749578c3113ff9eb19c9b';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
console.log(xhr);
alert('Woops, there was an error making the request.');
};
xhr.send();
}
makeCorsRequest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment