HTML and CSS Reference
In-Depth Information
Listing 6-7. CORS API Example
<!DOCTYPE HTML>
<head>
<script>
var call = new XMLHttpRequest();
var url = ' http://free.worldweatheronline.com/feed/weather.ashx?q=19043&format=json&num_of_
days=3&key=XXXXXXXXXXXXXX ' ;
function callOtherDomain() {
if(call) {
call.open('GET', url, true);
call.withCredentials = true;
call.onreadystatechange = gotThatData;
call.send();
}
}
function gotThatData (data) {
console.log(data)
}
callOtherDomain()
</script>
</head>
<body>
</body>
</html>
From the listing, you can see we're using the XMLHttpRequest object XMLHttpRequest object by writing
var call = new XMLHttpRequest(); . From there, we set up another variable, url , which will point to the free
weather service, where we're trying to access the information. Next, we set up a function, callOtherDomain() , which
will handle making the request to the domain and providing a callback to the function gotThatData() , where we
simply log out the response (if there is one).
If you're following along in your browser and make that request, first, you'll need your free API key for the
requestrequest to www.worldweatheronline.com , but after that, you should see something pretty interesting in the
browser's console—something like what you see in Figure 6-8 .
Figure 6-8. Demonstration of a failed CORS request
This message is pretty much telling you that the domain of the weather service is not set up, with CORS using the
origin of my localhost domain. If this weren't the case, you'd be able to see the response data in our browser.
For leveraging APIs where ads will need to pull in information from other domains, this means the server's
response headers will need to include some basic access by having Access-Control-Allow-Origin: * (for public)
or Access-Control-Allow-Origin: http://example.com (for protected). In the first example, it's a wildcard, thus
allowing any domain to access the information. In the latter, the URL will match whichever domain you're making
 
Search WWH ::




Custom Search