控制器POST操作响应“未授权”

时间:2017-05-25 09:27:07

标签: scala playframework

总的noobie问题,我刚刚开始使用Play框架。

我在控制器中添加了一个操作“添加”,当我尝试访问它时,我得到了以下页面,其中包含HTTP 403状态。

Unauthorized

控制器:

package controllers

import javax.inject._

import play.api._
import play.api.data._
import play.api.data.Forms._
import play.api.mvc._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject() extends Controller {

  val userForm = Form(
    mapping(
      "todo" -> text
    )(TodoData.apply)(TodoData.unapply)
  )

  /**
   * Create an Action to render an HTML page.
   *
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index = Action { implicit request =>
    Ok(views.html.index())
  }

  def add = Action { implicit request =>
    Ok(views.html.index())
  }
}
case class TodoData(todo: String)

路线

# An example controller showing a sample home page
GET     /                           controllers.HomeController.index
POST    /add                        controllers.HomeController.add

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

index.scala.html

@()

@main("Todo App") {
  <h1>Welcome to the Todo app</h1>
    <form action="/add" method="post">
        <label for="todo">TODO:</label>
        <input type="text" name="todo" id="todo">

        <button type="submit">Add</button>
    </form>
}

1 个答案:

答案 0 :(得分:1)

经过几个小时的挖掘后,我自己设法解决了这个问题。一例RTFM。

似乎有一些神奇的Play与POST请求和CSRF令牌有关。我错过了CSRF令牌。

我将表单更改为Play表单:

index.scala.html

@(form: Form[TodoData])(implicit request: RequestHeader, messages: Messages)

@main("Todo App") {
  <h1>Welcome to the Todo app</h1>
    @helper.form(action = routes.HomeController.add()) {
        @helper.CSRF.formField
        @helper.inputText(form("todo"))
        <button type="submit">Add</button>
    }
}

控制器

package controllers

import javax.inject._

import play.api.data._
import play.api.data.Forms._
import play.api.mvc._
import play.api.i18n._

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
@Singleton
class HomeController @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {

  val todoForm = Form(
    mapping(
      "todo" -> text
    )(TodoData.apply)(TodoData.unapply)
  )

  /**
   * Create an Action to render an HTML page.
   *
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index = Action { implicit request =>
    Ok(views.html.index(todoForm))
  }

  def add = Action { implicit request =>
    val errorFunction = { formWithErrors: Form[TodoData] =>
      // This is the bad case, where the form had validation errors.
      // Let's show the user the form again, with the errors highlighted.
      // Note how we pass the form with errors to the template.
      BadRequest(views.html.index(formWithErrors))
    }

    val successFunction = { data: TodoData =>
      // This is the good case, where the form was successfully parsed as a Data.

      Redirect(routes.HomeController.index()).flashing("info" -> "Todo task added!")
    }

    val formValidationResult = todoForm.bindFromRequest
    formValidationResult.fold(errorFunction, successFunction)
  }
}

case class TodoData(todo: String)