【问题标题】:Scalatra Set Response HeadersScalatra 设置响应标头
【发布时间】:2015-10-14 18:25:15
【问题描述】:

我正在尝试在发布请求期间设置响应标头。虽然一切都正确编译,但没有设置标题。

这是我的代码:

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
}

设置此类标头的有效方法是什么?

谢谢!

【问题讨论】:

    标签: scala post header scalatra


    【解决方案1】:

    我不熟悉 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)
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-24
      • 2013-08-02
      • 1970-01-01
      • 2021-07-27
      • 2017-08-28
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多