当我尝试提交表单Rocket Rust时给出错误422

时间:2020-05-03 19:00:29

标签: rust rust-rocket

我正在尝试创建一个表单来在Rocket Rust中创建帖子(我尚未访问db)。 当我尝试提交表单时,出现错误422。

错误:

POST /new_post application/x-www-form-urlencoded:
    => Matched: POST /new_post (new_post_form)
    => Error: The incoming form failed to parse.
    => Outcome: Failure
    => Warning: Responding with 422 Unprocessable Entity catcher.
    => Response succeeded.

处理程序代码:

#[post("/new_post", data="<form>")]
fn new_post_form(form: Form<NewPostForm>) -> Flash<Redirect>  {
    let form = form.into_inner();
    if form.body.is_empty() {
        Flash::error(Redirect::to("/new_post"), "NoBodyError");
    }
    if form.name.is_empty() {
        Flash::error(Redirect::to("/new_post"), "NoNameError");
    }
    if form.name.is_empty() && form.body.is_empty() {
        Flash::error(Redirect::to("/new_post"), "NoNameBodyError")
    } else {
        Flash::error(Redirect::to("/new_post"), "NoNameBodyError")
    }
}

表单结构:

#[derive(FromForm)]
pub struct NewPostForm {
    pub name: String,
    pub body: String
}

HTML表单:

<form action="/new_post" method="post">
  name:<input type="text" name="name" id="name">
  Body:<input type="text" name="body" id="body">
  <button type="submit" name="button"></button>
</form>

P.S。我认为问题出在HTML表单中,而不是Rust中。如果问题出在Rust中,它将给出另一个错误。

1 个答案:

答案 0 :(得分:0)

仅从代码片段很难理解这里到底是什么问题。我认为您应该尝试查看后端接收到的确切数据,并试图了解为什么代码生成的FromForm实现无法解析该数据。

您实际上可以自己实现FromForm特性。只需删除#[derive(FromForm)]并执行:

impl<'f> FromForm<'f> for NewPostForm {
    type Error = ();

    fn from_form(items: &mut FormItems<'f>, strict: bool) -> Result<NewPostForm, ()> {
        // Inspect `items` here
        // ...
    }
}