简体   繁体   中英

Java Play Framework 2.6 does not return `Access-Control-Allow-Origin` CORS header

Play does not honor my application.conf configuration to return a Access-Control-Allow-Origin header. When I send a request from Ajax, the response is always:

Failed to load http://localhost:9000/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

This is what my application.conf looks like:

# disable the built in filters
play.http.filters = play.api.http.NoHttpFilters

play.filters.enabled += "play.filters.cors.CORSFilter"

play.filters {
    cors {
    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null
   }
}

The only way I have succeeded in getting the Ajax request through, is by adding the line response().setHeader("Access-Control-Allow-Origin", "*"); in the controller. But I want to do it through application.conf so I don't have to add this setHeader() code in all the controllers.

public class HomeController extends Controller {

    public Result index() {
        // this is the only hack that works
        //response().setHeader("Access-Control-Allow-Origin", "*");

        return ok(
            Json.toJson("A long time ago in a galaxy far, far away....")
        );
    }
}

My Ajax request looks like this:

$.ajax({
    url: "http://localhost:9000",
    type: "GET",
    dataType: 'json',
    success: function(_out) {
        alert(_out);
    },
    fail: function() {
        alert("error");
    }
});

Why is Play not honoring my application.conf configuration for CORS?

I have determined the problem. In my application.conf :

play.http.filters = play.api.http.NoHttpFilters

play.filters.enabled += "play.filters.cors.CORSFilter"

These two lines are not additive. In other words, the first line disables all filters and the second line enables a filter, but the end result is still that all filters are disabled (even though ENabling comes AFTER DIsabling).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM