I'm using Play 2.2.1 and I'm trying to write my own Action to deal with CORS requests. I found this but unfortunately it doesn't compile.
Just for reference here's the (slightly modified) code:
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"
))
}
}
}
The error is:
Cors.scala:13: not found: value Ok
I'm very new to Scala and even more so to Play! and can't figure out what's going on. As far as I know I have to use EssentialAction and not just Action b/c I want to get to the header of the request. All the examples I found so far involve only Action.
You need to import the Results trait -- the Ok val is defined there.
http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.mvc.Results
As Will said you are missing the the
Results
trait.A probably cleaner way to implement the
CorsAction
would be to useActionBuilders
as described in http://www.playframework.com/documentation/2.2.x/ScalaActionsCompositionThe implementation would look like this: