Here is some background information...
- 1) http://www.html5rocks.com/en/tutorials/cors/ - Note that you need to read the bit about "not so simple requests" as JSon falls into this category.
- 2) http://stackoverflow.com/questions/9613210/cors-access-control-allow-origin-despite-correct-headers?rq=1
- 3) http://caniuse.com/#search=cors - Details browsers that support CORS
- 4) http://stackoverflow.com/questions/10748537/access-control-allow-origin-on-playframework (for Play 1 NOT Play 2)
So here is what I implemented:
As not-so-simple-requests (see 1 above) make a pre-flight call, you need to add the following to the routes file:
POST /url_to_json_webservice controllers.myJsonWebServices.myJsonWebService
OPTIONS /url_to_json_webservice controllers.myJsonWebServices.checkPreFlight
and then set up the following method in your controller:
public static Result checkPreFlight() {
response().setHeader("Access-Control-Allow-Origin", "*"); // Need to add the correct domain in here!!
response().setHeader("Access-Control-Allow-Methods", "POST"); // Only allow POST
response().setHeader("Access-Control-Max-Age", "300"); // Cache response for 5 minutes
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // Ensure this header is also allowed!
return ok();
}
Note i may have set more headers than needed here, so please check which ones you need!!
Also remember to add the following to the end of your controller method that returns the actually JSon result (as in my question above):
public static Result myJsonWebService() {
...
response().setHeader("Access-Control-Allow-Origin", "*");
return ok(toJson(jsonObject));
}