Scalatra 设置响应 Headers

Scalatra Set Response Headers

我正在尝试在 post 请求期间设置响应 headers。虽然一切都正确编译,但未设置 headers。

这是我的代码:

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
}

设置这种 headers 的有效方法是什么?

谢谢!

我不熟悉 Scalatra,但您可以注意到 ActionResult 是一个案例 class;

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

本例class的第三个参数是Map[String,String],应该是响应头。

还有;

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

Returns 带有状态码 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)
}