Java Play 框架 2.6 没有返回 `Access-Control-Allow-Origin` CORS 头信息。

3

Play框架没有遵循我的application.conf配置返回一个Access-Control-Allow-Origin头。当我从Ajax发送请求时,响应总是:

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.

这是我的application.conf的样子:

# 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
   }
}

我成功发起Ajax请求的唯一方式是在控制器中添加这行代码:response().setHeader("Access-Control-Allow-Origin", "*");但我想通过application.conf来实现,这样我就不用在所有的控制器中添加setHeader()代码了。

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....")
        );
    }
}

我的Ajax请求如下:

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

为什么Play没有遵循我的application.conf配置来处理CORS?
1个回答

1
我已经确定了问题。在我的application.conf文件中:
play.http.filters = play.api.http.NoHttpFilters

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

这两行代码不是相加的。换句话说,第一行代码禁用了所有过滤器,而第二行代码启用了一个过滤器,但最终结果仍然是所有过滤器都被禁用了(即使启用操作在禁用操作之后执行)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接