Cross domain scripting can cause a lot of frustration when developing web applications, especially when doing initial development work. When working strictly on a local machine, it shouldn’t matter that information needs to be called from one port and consumed by another. Cross domain issues occur not only when JavaScript/JSON is being called between two different domains, but it also occurs on the same domain between two different ports.
Typically when debugging this type of JavaScript issue you’ll encounter a message like the one below:
XMLHttpRequest cannot load http://localhost:8080/some.json.
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:8090’ is therefore not allowed access.
When faced with this issue there are typically 2 ways to get around it:
- Wrap the data being requested in JSONP
- Enable CORS on the web server making the request
(CORS stands for Cross-origin resource sharing)
Number one above is outside the scope of this article, but there are plenty of good articles on this topic. I find that this solution is a bit overkill, especially for initial development.
The second option can be much simpler, especially if you are running an Apache Web Server. If you are running Apache locally but your production systems are not, then you may want to weigh both options and find out which will work best. In both cases you’ll need to make server side configuration so I find that enabling CORS via the Apache config file is the way to go.
To enable CORS via the Apache config (usually http.conf) simply add the line below and restart Apache.
Header set Access-Control-Allow-Origin *
This will not fly in a production environment as this may not be strict enough. In that case you can target one or more domains to allow (instead of using *):
set Access-Control-Allow-Origin: http://localhost:8080 http://domain.com
This allows only access to http://localhost:8080 (as in my error message in the beginning) and also to the site domain.com (over the standard port 80).
If you’re not using Apache (or even if you are), enable-cors.org has tons of information on the subject. If you are using Apache this should be a quick and easy fix around the cross domain scripting problem mentioned above.