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不尊重我的CORSapplication.conf
配置?
我已经确定了这个问题。在我的application.conf
:中
play.http.filters = play.api.http.NoHttpFilters
play.filters.enabled += "play.filters.cors.CORSFilter"
这两行不是相加的。换句话说,第一行禁用所有过滤器,第二行启用过滤器,但最终结果仍然是所有过滤器都被禁用(即使启用是在DIsabling之后(。