我想在Play 2.2.x应用程序中实现一个CORS过滤器。到目前为止,我有以下内容:
package filters
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.GlobalSettings
class CorsFilter extends EssentialFilter {
def apply(next: EssentialAction) = new EssentialAction {
def apply(requestHeader: RequestHeader) = {
next(requestHeader).map { result =>
result.withHeaders("Access-Control-Allow-Origin" -> "*",
"Access-Control-Expose-Headers" -> "WWW-Authenticate, Server-Authorization",
"Access-Control-Allow-Methods" -> "POST, GET, OPTIONS, PUT, DELETE",
"Access-Control-Allow-Headers" -> "x-requested-with,content-type,Cache-Control,Pragma,Date")
}
}
}
}
object Global extends WithFilters(new CorsFilter) with GlobalSettings
以及预检选项操作:
def preflight(all: String) = Action {
Ok("").withHeaders("Access-Control-Allow-Origin" -> "*",
"Allow" -> "*",
"Access-Control-Allow-Methods" -> "POST, GET, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers" -> "Origin, X-Requested-With, Content-Type, Accept, Referrer, User-Agent");
}
定义了路线:
OPTIONS /*all controllers.Application.preflight(all: String)
似乎正在发生的事情是CorsFilter代码没有被执行。我打开了调试器,但是我没有看到任何请求到达此过滤器。为什么会这样?是否有其他地方我需要定义过滤器的东西,以便Play可以看到它?
答案 0 :(得分:3)
GlobalSettings
对象需要在默认包中,因此package filters
会导致Play忽略它。我建议将其移至自己的文件Global.scala
。
答案 1 :(得分:3)
对于类似的项目,尝试让AngularJS Web客户端与Scala服务器通信,您使用的标头不起作用。我们用过:
ACCESS_CONTROL_ALLOW_ORIGIN -> "*",
ACCESS_CONTROL_ALLOW_METHODS -> "GET, POST, OPTIONS",
ACCESS_CONTROL_ALLOW_HEADERS -> "Origin, Accept, Authorization, X-Auth-Token",
ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
我们在LimbSoup建议的自己的文件中有了Global对象。我们从https://gist.github.com/jeantil/7214962借用了代码的支柱,但对代码进行了硬编码,而不是以编程方式实现它们。