posted 12-Sep-2012 | no comments | , , , , ,

Most modern browsers restrict access for all Javascript requests made from a page, allowing only requests made to the server from where the page was loaded. This (same origin policy) is generally a good idea since it goes a long way to prevent XSS.

But sometimes you need that kind of access, for example when developing an HTML based mobile app that retrieves dynamic content from a web server. In that scenario the web pages are run locally in the mobile device (smartphone or tablet) and they make requests and posts to your remote web server, which is by default not allowed.

You can go around this by just modifying the web server response to include the Access-Control-Allow-Origin header with a valid origin value. For example:

Access-Control-Allow-Origin: *

Will allow all requests from all origins.

You can configure this to be sent on the desired requests on your web server, or you can just add the header programatically on each page/service you need, for example in PHP you can just add:

<?php header('Access-Control-Allow-Origin: *'); ?>