播放2.0.1并设置Access-Control-Allow-Origin

mst*_*ffo 13 javascript xmlhttprequest http-headers playframework-2.0

我有一个Play 2.0.1应用程序,我想使用托管在其他域上的Javascript调用.我的Javascript调用失败了:

Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)

我已经找到了一些如何在Play 1中设置正确的HTTP标头的例子,但是没有为Play 2.0.1找到任何东西.在阅读文档(http://www.playframework.org/documentation/2.0.2/JavaResponse)之后,我尝试了以下方法以使工作正常:

public static Result myJsonWebService() {
  ...
  response().setHeader("Access-Control-Allow-Origin", "*");
  return ok(toJson(jsonObject));
}
Run Code Online (Sandbox Code Playgroud)

但我的JS Web服务调用仍然失败.

为了让这个工作,我需要做什么?

Lor*_*Goo 14

对于Scala人来说,这是我目前正在使用的实现:

import play.api.mvc._
import scala.concurrent._
import play.api.http.HeaderNames._

/**
 * Action decorator that provide CORS support
 *
 * @author Giovanni Costagliola, Nick McCready
 */
case class WithCors(httpVerbs: String*)(action: EssentialAction) extends EssentialAction with Results {
    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") { // preflight
            val corsAction = Action {
                request =>
                    Ok("").withHeaders(
                        ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
                        ACCESS_CONTROL_ALLOW_METHODS -> (httpVerbs.toSet + "OPTIONS").mkString(", "),
                        ACCESS_CONTROL_MAX_AGE -> "3600",
                        ACCESS_CONTROL_ALLOW_HEADERS ->  s"$ORIGIN, X-Requested-With, $CONTENT_TYPE, $ACCEPT, $AUTHORIZATION, X-Auth-Token",
                        ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true")
            }
            corsAction(request)
        } else { // actual request
            action(request).map(res => res.withHeaders(
                ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
                ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
            ))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,只需按以下方式装饰您的操作:

def myAction = WithCors("GET", "POST") {
  Action { request =>
    ???
  }
}
Run Code Online (Sandbox Code Playgroud)


mst*_*ffo 11

这是一些背景信息......

  • 1)http://www.html5rocks.com/en/tutorials/cors/ - 请注意,您需要阅读有关"不那么简单的请求"的内容,因为JSon属于此类别.
  • 2)http://stackoverflow.com/questions/9613210/cors-access-control-allow-origin-despite-correct-headers?rq=1
  • 3)http://caniuse.com/#search=cors - 详细说明支持CORS的浏览器
  • 4)http://stackoverflow.com/questions/10748537/access-control-allow-origin-on-playframework(适用于Play 1 NOT Play 2)

所以这是我实施的:

由于不那么简单的请求(参见上面的1)进行飞行前呼叫,您需要将以下内容添加到路由文件中:

POST /url_to_json_webservice        controllers.myJsonWebServices.myJsonWebService
OPTIONS /url_to_json_webservice     controllers.myJsonWebServices.checkPreFlight
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中设置以下方法:

public static Result checkPreFlight() {
    response().setHeader("Access-Control-Allow-Origin", "*");       // Need to add the correct domain in here!!
    response().setHeader("Access-Control-Allow-Methods", "POST");   // Only allow POST
    response().setHeader("Access-Control-Max-Age", "300");          // Cache response for 5 minutes
    response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");         // Ensure this header is also allowed!  
    return ok();
}
Run Code Online (Sandbox Code Playgroud)

注意我可能在这里设置了比所需更多的标题,所以请检查你需要的标题!

还记得在控制器方法的末尾添加以下内容,返回实际的JSon结果(如上面的问题所示):

public static Result myJsonWebService() {
  ...
  response().setHeader("Access-Control-Allow-Origin", "*");
  return ok(toJson(jsonObject));
}
Run Code Online (Sandbox Code Playgroud)