0

I'm trying to go something really simple with Playframework Scala (2.3): create a route POST and get POST parameters.

The route definition

POST    /ff/user                controllers.Application.createUser

The controller

def createUser = Action.async { request =>
    val user = request.queryString.get("user").flatMap(_.headOption)
    val email = request.queryString.get("email").flatMap(_.headOption)
    val firstname = request.queryString.get("firstname").flatMap(_.headOption)
    val lastname = request.queryString.get("lastname").flatMap(_.headOption)

    Logger.debug("Create User")
    Logger.debug(s"user=$user")
    Logger.debug(s"email=$email")

    Ok("Youpi")
}

When I post a request to /ff/user, the log says : user=None, email=None. I cannot figure out why they are "None". What is wrong?

Thank for helping.

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
Greg
  • 167
  • 2
  • 10

1 Answers1

2

When using a POST like this, you probably want to look at the body field on the request parameter, which will contain the form that was posted. You usually don't use a query string with POST requests (more about that here). So, that might look like:

def createUser = Action.async { request =>
    val user = request.body.asFormUrlEncoded.get.get("user").head
    Future(Ok())
}

You might also want to use the Action.async overload that provides a parsed body. For example, it might look like:

def createUser = Action.async(parse.urlFormEncoded) { request =>
   //body is already treated as a Map[String, Seq[String]] because of the parameter passed to async
   val user = request.body("user").head 
   Future(Ok())
}
Community
  • 1
  • 1
Ben Reich
  • 16,222
  • 2
  • 38
  • 59