HTML and CSS Reference
In-Depth Information
Listing 6-7. CORS API Example
var call = new XMLHttpRequest();
var url = '
days=3&key=XXXXXXXXXXXXXX ' ;
function callOtherDomain() {
if(call) {'GET', url, true);
call.withCredentials = true;
call.onreadystatechange = gotThatData;
function gotThatData (data) {
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 , 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: (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