如何修复Rocket框架中POST表单请求的解析错误?
Hey there! The root cause of your 422 error is a mismatch between your HTML form field name and your Rocket FromForm struct field name—let's break this down and fix it.
The Problem
Your HTML form has an input with name="searchterm":
<input type="text" name="searchterm">
But your Request struct defines a field named payload:
#[derive(FromForm)] pub struct Request<'r> { payload: &'r RawStr, }
Rocket's FromForm macro relies on exact name matching to parse form data. Since it can't find a form field named payload, it throws the 422 error.
The Fixes
You have two simple ways to resolve this:
1. Match the struct field name to the form field name
Rename the struct field to searchterm to directly match the form's input name:
#[derive(FromForm)] pub struct Request<'r> { searchterm: &'r RawStr, // Now matches the form's "searchterm" field } #[post("/search", data = "<data>")] pub fn process(data: Form<Request>) -> Result<Redirect, String> { // Update the reference to use the new field name if data.searchterm == "Hello!" { Ok(Redirect::to("/search/Hello")) } else { Err(format!("Unknown search term, '{}'.", data.searchterm)) } }
2. Use a field alias (keep your struct field name)
If you want to keep the payload field name in your struct, use Rocket's #[field(name = "...")] attribute to map it to the form's searchterm field:
#[derive(FromForm)] pub struct Request<'r> { #[field(name = "searchterm")] // Map this field to the form's "searchterm" input payload: &'r RawStr, } // Your existing process function stays the same since we're keeping the payload field name #[post("/search", data = "<data>")] pub fn process(data: Form<Request>) -> Result<Redirect, String> { if data.payload == "Hello!" { Ok(Redirect::to("/search/Hello")) } else { Err(format!("Unknown search term, '{}'.", data.payload)) } }
Testing It Out
After applying either fix, submit your form with "Hello!" as the search term—you'll no longer get the 422 error, and you'll be redirected to the GET route as expected. Your existing GET handler works fine because it's matching the path parameter directly, which doesn't rely on form field names.
Quick Tip
For future form fields, always ensure the form input's name attribute matches either your struct field name or the alias specified via #[field(name = "...")]. Rocket's form parsing is strict about this, but it's easy to get right once you know the rule!
内容的提问来源于stack exchange,提问作者Adrian Bernat




