在 Play Framework 2.4 for Scala 中实现 CORS

Implementing CORS in Play Framework 2.4 for Scala

我还没有成功地让 CORS 请求在我的项目中工作,基本上是一个 Play 服务器和一个 AngularJS 网络客户端。

由于要考虑的变量很多,我想首先确保至少在 Play 服务器端一切正常。但是,我的错,Play 2.4 documentation on CORS 不足以帮助我找出一个具体的用例。

两个基本问题:

  1. 在项目的根目录中创建过滤器 class(请参阅 docs):将提供的代码放在哪里?不确定 "root of your project" 是什么,我在 app/controllers/Mycontr.scala
  2. 中将 class 添加到我的控制器
  3. 文档中描述的要点是否足够?或者其他部分也需要触及,例如app/conf/routes
  4. 中的路由

试图找到完整的教程,但没有找到 Play 2.4

"root of your project"表示对应包根的目录。默认为app/,使用default sbt layout时为src/main/scala/。就这些了。

我 运行 遇到了同样的问题,它一直在说:

XMLHttpRequest cannot load http://localhost:9000/fetchBetween. Response to preflight request doesn't pass access control check: No 'Access-Control Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.

我将 Filters.scala 添加到我的 app/ 文件夹,并将 filters 添加到 libraryDependencies,这是我在 application.conf 中的配置:

play.filters.cors {

  pathPrefixes = ["/fetchBetween"]

  allowedOrigins = ["*"]

  allowedHttpMethods = ["GET", "POST"]

  allowedHttpHeaders = ["Accept"]

  preflightMaxAge = 3 days

}