2013-02-11 174 views

回答

2

不知道这如何转换为2.x,但在1.2.5中,我所做的是这样的。如果您有非标准标题,Access-Control-Allow-Headers是可选的。您可以将Allow-Origin的*更改为仅匹配您想要允许的域。

@Before 
static void CORS() { 
    if(request.headers.containsKey("origin")){ 
     response.headers.put("Access-Control-Allow-Origin", new Header("Access-Control-Allow-Origin", "*")); 
     response.headers.put("Access-Control-Allow-Headers", new Header("Access-Control-Allow-Headers", "my-custom-header, my-second-custom-header")); 
    } 
} 

如果有非标方法(GET/POST),或使用自定义页眉,大多数用户代理将有预检OPTIONS调用,所以你什么,我要做的就是将它添加到我的路线文件:

#This catches the preflight CORS calls 
OPTIONS /{path}         Application.options 

,这在我的控制器:

/** 
* Cross Origin Request Sharing calls are going to have a pre-flight option call because we use the "non simple headers" 
* This method catches those, (headers handling is done in the CORS() method) 
*/ 
public static void options() {} 
2

使用Scala语言,一个很好的和简单的PlayFramework的解决办法是使用以下ActionBuilder

import play.api.mvc._ 
import scala.concurrent.Future 
import scala.concurrent.ExecutionContext.Implicits.global 

// An Actionbuilder for CORS - Cross Origin Resource Sharing 
object CorsAction extends ActionBuilder[Request] { 

    def invokeBlock[A](request: Request[A], block: (Request[A]) ⇒ Future[SimpleResult]): Future[SimpleResult] = { 
    block(request).map { result => 
     request.headers.get("Origin") match { 
     case Some(o) => result.withHeaders("Access-Control-Allow-Origin" -> o) 
     case None => result 
     } 
    } 
    } 
} 

ActionBuilder重写invokeBlock方法,目的是将您的应用程序控制器操作创建的结果(由Play> = 2.1中的Future对象包装)映射到具有额外的“Access-Control-Allow -Origin“标题字段,如果请求带有”Origin“标题字段。

上述动作构建器可以被简单地使用如下:

object MyController extends Controller { 

    def myAction = CorsAction { 
    Ok("whatever HTML or JSON you want") 
    // it will be certainly processed by your browser 
    } 
}