【问题标题】:Java Play Framework 2.6 does not return `Access-Control-Allow-Origin` CORS headerJava Play Framework 2.6 不返回“Access-Control-Allow-Origin”CORS 标头
【发布时间】:2019-03-31 11:59:14
【问题描述】:

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 不支持我的 CORS application.conf 配置?

【问题讨论】:

    标签: java playframework cors playback


    【解决方案1】:

    我已经确定了问题。在我的application.conf:

    play.http.filters = play.api.http.NoHttpFilters
    
    play.filters.enabled += "play.filters.cors.CORSFilter"
    

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

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 2019-06-19
      • 2018-09-19
      • 2013-07-08
      • 2019-02-07
      • 2016-10-30
      • 1970-01-01
      相关资源
      最近更新 更多