我正在使用Play 2.2.1而我正在尝试编写自己的Action来处理CORS请求。我找到了this,但不幸的是它没有编译。
仅供参考,这是(略微修改过的)代码:
import play.api.mvc._
import scala.concurrent.ExecutionContext
case class CorsAction(action: EssentialAction) extends EssentialAction {
def apply(request: RequestHeader) = {
implicit val executionContext: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext
val origin = request.headers.get("Origin").getOrElse("*")
if (request.method == "OPTIONS") {
val cors = Action { request =>
Ok("").withHeaders(
"Access-Control-Allow-Origin" -> origin,
"Access-Control-Allow-Methods" -> "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers" -> "Accept, Origin, Content-type, Authorization, X-Auth-Token, " +
"X-HTTP-Method-Override, X-Json, X-Prototype-Version, X-Requested-With",
"Access-Control-Allow-Credentials" -> "true",
"Access-Control-Max-Age" -> (60 * 60 * 24 * 30).toString)
}
cors(request)
} else {
action(request).map(res =>
res.withHeaders(
"Access-Control-Allow-Origin" -> origin,
"Access-Control-Allow-Credentials" -> "true"
))
}
}
}
错误是:
Cors.scala:13: not found: value Ok
我是Scala的新手,玩游戏更是如此!并且无法弄清楚发生了什么。据我所知,我有使用EssentialAction而不仅仅是Action b / c我想要获取请求的标题。到目前为止我发现的所有例子都只涉及Action。
答案 0 :(得分:5)
威尔说你错过了Results
特质。
实现CorsAction
的一种可能更简洁的方法是使用ActionBuilders
,如中所述
http://www.playframework.com/documentation/2.2.x/ScalaActionsComposition
实现如下:
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
object CorsAction extends ActionBuilder[Request] with Results{
val MaxAge = 60 * 60 * 24 * 30
val AllowHeaders = List(
"Accept", "Origin", "Content-type", "Authorization", "X-Auth-Token",
"X-HTTP-Method-Override", "X-Json", "X-Prototype-Version", "X-Requested-With")
val AllowMethods = List("GET", "POST", "PUT", "DELETE", "OPTIONS")
val AllowCredentials = true
def cors[A](origin: String) =
Ok.withHeaders(
"Access-Control-Allow-Origin" -> origin,
"Access-Control-Allow-Methods" -> AllowMethods.mkString(", "),
"Access-Control-Allow-Headers" -> AllowHeaders.mkString(", "),
"Access-Control-Allow-Credentials" -> AllowCredentials.toString,
"Access-Control-Max-Age" -> MaxAge.toString)
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[SimpleResult]) = {
implicit val executionContext = play.api.libs.concurrent.Execution.defaultContext
val origin = request.headers.get("Origin").getOrElse("*")
if (request.method == "OPTIONS") {
Future.successful(cors(origin))
} else {
block(request).map(res =>
res.withHeaders(
"Access-Control-Allow-Origin" -> origin,
"Access-Control-Allow-Credentials" -> AllowCredentials.toString
))
}
}
}
答案 1 :(得分:1)
您需要导入结果特征 - 在那里定义了Ok值。
http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.mvc.Results