2015-10-14 103 views
1

我試圖在post請求期間設置響應頭文件。雖然一切正常編譯,標題沒有設置。Scalatra設置響應頭文件

這裏是我的代碼:

post("/get_value"){ 
val jsonString = request.body; 

    response.setHeader("Access-Control-Allow-Origin", "*") 
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE") 
    response.setHeader("Access-Control-Max-Age", "3600") 
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type") 

jsonString 
} 

什麼是設置這樣的報頭的有效方法是什麼?

謝謝!

回答

2

我不熟悉Scalatra,但你可以注意到ActionResult是一個案例類;

case class ActionResult(status: ResponseStatus, body: Any, headers: Map[String, String]) 

本案例類的第三個參數是Map[String,String],它應該是響應頭。

還有;

object Ok { 
    def apply(body: Any = Unit, headers: Map[String, String] = Map.empty, reason: String = "") = ActionResult(responseStatus(200, reason), body, headers) 
} 

返回狀態碼爲200的http響應,您可以像創建它那樣;

Ok("response",Map('HeaderKey' -> 'HeaderValue')) 

作爲一個結論最終的解決方案可以像;

post("/get_value") { 
    val jsonString = request.body; 
    val headers = Map("Access-Control-Allow-Origin" -> "*", 
        "Access-Control-Allow-Methods" -> "POST, GET, OPTIONS, DELETE", 
        "Access-Control-Max-Age" -> "3600", 
        "Access-Control-Allow-Headers" -> "x-requested-with, content-type") 

    Ok(jsonString,headers) 
}