2

I am trying to set response headers during post request. While everything compiles properly, headers are not set.

Here is my code:

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
}

What is the valid way to set headers of this kind?

Thanks!

nietsnegttiw
  • 371
  • 1
  • 5
  • 16

1 Answers1

2

I'm not familiar with Scalatra but you can notice that ActionResult is a case class;

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

3rd parameter of this case class is Map[String,String] which should be response header.

There is also;

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

Returns http response with status code 200, you can create it like;

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

As a conclusion final solution can be like;

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)
}
Fatih Donmez
  • 4,319
  • 3
  • 33
  • 45