Skip to content

Instantly share code, notes, and snippets.

@eljefedelrodeodeljefe
Last active August 29, 2015 14:13
Show Gist options
  • Save eljefedelrodeodeljefe/3da84fa6fde600903dc2 to your computer and use it in GitHub Desktop.
Save eljefedelrodeodeljefe/3da84fa6fde600903dc2 to your computer and use it in GitHub Desktop.
CORS XMHttpRequest REST-ful API-call
function loadPhotos() {
var api_key = '<YOUR API KEY HERE>';
var method = 'GET';
var url = 'https://api.flickr.com/services/rest/?' +
'method=flickr.people.getPublicPhotos&' +
'user_id=32951986%40N05&' +
'extras=url_q&format=json&nojsoncallback=1&' +
'api_key=' + api_key;
var xhr = new XMLHttpRequest();
if (!('withCredentials' in xhr)) {
alert('Browser does not support CORS.');
return;
}
xhr.open(method, url);
xhr.onerror = function() {
alert('There was an error.');
};
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
if (data.stat == 'ok') {
var photosDiv = document.getElementById('photos');
photosDiv.innerHTML = '';
var photos = data.photos.photo;
for (var i = 0; i < photos.length; i++) {
var img = document.createElement('img');
img.src = photos[i].url_q;
photosDiv.appendChild(img);
}
} else {
alert(data.message);
}
};
xhr.send();
}
This was the only working example I could find for a decent CORS REST call.
The original is from [CORSinAction](https://github.com/monsur/CORSinAction). Thanks for your nice books guys.
When you provide it with a valid API-key, the programm will fill your <body> with tiles of the numerous images
grabbed via the API. It's indeed a very nice example.
[link to working JS.bin](http://jsbin.com/yetudidiwo)
<!DOCTYPE html>
<html>
<body onload="loadPhotos();">
<div id="photos">Loading photos...</div>
<script async="async" src="bundle.js" type="text/javascript"></script>
</body>
</html>
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Controller/Action");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(JSON.stringify(myData));
var req = new XMLHttpRequest();
var body = // JSON.stringify(productData) or something
if ('withCredentials' in req) {
req.open('POST', 'http://api.foo.com/products', true);
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('Api-Key', 'foobar');
req.onreadystatechange = handleResponse;
req.send(body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment