我有一个Play 2.0.1应用程序,我想使用托管在其他域上的Javascript调用。我的Javascript调用失败了:
Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.
我找到了一些如何在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));
}
但我的JS网络服务调用仍然失败。
我需要做些什么来实现这个目标?
答案 0 :(得分: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"
))
}
}
}
要使用它,只需按以下方式装饰您的动作:
def myAction = WithCors("GET", "POST") {
Action { request =>
???
}
}
答案 1 :(得分:11)
以下是一些背景信息......
所以这就是我实施的内容:
由于不那么简单的请求(参见上面的1)进行飞行前呼叫,您需要将以下内容添加到路线文件中:
POST /url_to_json_webservice controllers.myJsonWebServices.myJsonWebService
OPTIONS /url_to_json_webservice controllers.myJsonWebServices.checkPreFlight
然后在控制器中设置以下方法:
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();
}
注意我可能在这里设置了比所需更多的标题,所以请检查你需要的标题!!
还记得在控制器方法的末尾添加以下内容,返回实际的JSon结果(如上面的问题所示):
public static Result myJsonWebService() {
...
response().setHeader("Access-Control-Allow-Origin", "*");
return ok(toJson(jsonObject));
}
答案 2 :(得分:3)
这样做的好方法是扩展操作:
package actions;
import play.*;
import play.mvc.*;
import play.mvc.Http.Context;
import play.mvc.Http.Response;
public class CorsAction extends Action.Simple {
public Result call(Context context) throws Throwable{
Response response = context.response();
response.setHeader("Access-Control-Allow-Origin", "*");
//Handle preflight requests
if(context.request().method().equals("OPTIONS")) {
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token");
response.setHeader("Access-Control-Allow-Credentials", "true");
return ok();
}
response.setHeader("Access-Control-Allow-Headers","X-Requested-With, Content-Type, X-Auth-Token");
return delegate.call(context);
}
}
然后在您的控制器中添加以下行:
@With(CorsAction.class)
然后所有ok()请求都会响应上面的标题。
答案 3 :(得分:1)
实现为Scala过滤器(播放2.2.x):
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc._
import play.api.mvc.Results._
import play.api.http.HeaderNames._
object Cors extends Filter {
def apply(next: (RequestHeader) => Future[SimpleResult])(request: RequestHeader): Future[SimpleResult] = {
val origin = request.headers.get(ORIGIN).getOrElse("*")
if (request.method == "OPTIONS") {
val response = Ok.withHeaders(
ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
ACCESS_CONTROL_ALLOW_METHODS -> "POST, GET, OPTIONS, PUT, DELETE",
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"
)
Future.successful(response)
} else {
next(request).map {
res => res.withHeaders(
ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
)
}
}
}
}
object Global extends WithFilters(Cors) {...}