When trying to access your data tier, you [may] encounter the browser’s built in security feature that does not allow you to make XMLHttpRequest object requests to a different domain (see Same Origin Policy).
UPDATE 10-24-2012: To get CORS working in IE8 and IE9, use
XDomainRequest using the object’s
onload (the equivalent of the
onreadystatechange event). IE10 natively supports CORS using XMLHttpRequest.
UPDATE 10-21-2012: Well, I had some pretty significant issues trying to get CORS working across a different sub-domain AND port. In my case, the origin server was
https://my.server.com and the request server was
https://other.server.com:5555. Using only the below technique did not work. After some extensive research and some help with a colleague of mine, we figured it out. Here are the changes we did to get it up and running with the above scenario.
DISCLAIMER: THIS ONLY WORKS WITH CHROME, SAFARI, AND FIREFOX! INTERNET EXPLORER (VERSION 9 IN MY CASE) DID NOT WORK. I DID SOME INITIAL RESEARCH AND FOUND THAT YOU MAY HAVE TO USE
XDomainRequest FOR ANY CROSS DOMAIN REQUESTS IN IE8 AND IE9 INSTEAD OF
XMLHttpRequest. HERE IS A GOOD ARTICLE ON HOW CORS WORKS IN IE9.
Now that we have the disclaimer out of the way, you’ll need to add the following to your web server response headers:
Access-Control-Allow-Origin: https://other.server.com:5555 Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: OPTIONS, GET, POST Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control
Next, I’ve seen this specifically in Chrome and Firefox. What essentially occurs is that the browser will send an initial OPTIONS request for the cross domain resource first. The browser then verifies from the cross domain server that
Access-Control-Allow-Origin is ALSO enabled. So you’ll need to make sure that the following is set on the cross domain server specifically for the resource being requested:
Access-Control-Allow-Origin: * Access-Control-Allow-Headers: X-Requested-With
It’s probably a good idea to keep the
Access-Control-Allow-Origin to be set at
- Use JSONP (JSON with padding)
- Use CORS (Cross-origin resource sharing)
CORS is accomplished by simply sending a specific header from the server:
Access-Control-Allow-Origin: http://domain.com:8080 http://foo.domain.com http://*.domain.com
There are other headers available, as specified from W3. Note that most of the major web browsers support CORS (e.g. Gecko based browsers such as Firefox, WebKit based browsers such as Chrome and Safari, and Trident based browsers such as IE). For more info on supported browsers, see Wikipedia.