Play 不遵循我的 application.conf
配置来返回 Access-Control-Allow-Origin
header 。当我从 Ajax 发送请求时,响应始终是:
无法加载 http://localhost:9000/:请求的资源上不存在“Access-Control-Allow-Origin” header 。因此,不允许访问源“null”。
这就是我的 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", "*");
Controller 。但我想通过 application.conf
来完成此操作,因此我不必在所有 Controller 中添加此 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
配置?
最佳答案
我已经确定了问题所在。在我的 application.conf
中:
play.http.filters = play.api.http.NoHttpFilters
play.filters.enabled += "play.filters.cors.CORSFilter"
这两行不是相加的。换句话说,第一行禁用所有过滤器,第二行启用一个过滤器,但最终结果仍然是所有过滤器都被禁用(即使 ENabling 在 DISabling 之后出现)。
关于Java Play Framework 2.6 不返回 `Access-Control-Allow-Origin` CORS header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53013558/