Forwarding in Play for Scala returns empty respons

2019-09-12 04:01发布

问题:

The HTTP forward below (futureResponse function) returns an empty response to the browser. Any ideas what is wrong and/or where should I look at?

  val request: WSRequest = ws.url("http://somehost/url2")
  val request2: WSRequest = request.withHeaders("Accept" -> "application/json")
  val data = Json.obj(
        "aaa" -> some_data1,
        "bbb" -> some_data2
   )
   val futureResponse: Future[JsValue] = request2.post(data).map {
     response => 
         val json= Json.obj(
             "ccc" -> "111",
             "ddd" -> "222"
            )
         json
   }

   Ok(json)

When I get the message in the browser, the data in the response is empty:

回答1:

Make the action asynchronous and reply a Future[Result], like:

def someAction = Action.async { implicit request =>
  val request: WSRequest = ws.url("http://somehost/url2")
  val request2: WSRequest = request.withHeaders("Accept" -> "application/json")
  val data = Json.obj(
    "aaa" -> some_data1,
    "bbb" -> some_data2
  )
  val futureResponse: Future[JsValue] = request2.post(data).map { response => 
     val json= Json.obj(
         "ccc" -> "111",
         "ddd" -> "222"
     )

     Ok(json)
  }

  futureResponse
}