2013-02-11 176 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 
    } 
}