使用 actix-web 捕获来自 HTML 页面的 GET 和 POST 请求

Cli*_*ger 5 rust actix-web

我在提交 HTML 表单以捕获 FORM 中请求的详细信息时收到一条错误消息(我正在使用 actix-web)。

当我提交表格时,我收到此错误:

Content type error

使用的代码:

#[derive(Deserialize)]
struct FormData {
    paire: String,
}


fn showit(form: web::Form<FormData>) -> String {
    println!("Value to show: {}", form.paire);
    form.paire.clone()
}

....

.service(
  web::resource("/")
    .route(web::get().to(showit))
    .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
))

Run Code Online (Sandbox Code Playgroud)

使用的 HTML 表单:

<form action="http://127.0.0.1:8080/" method="get">
<input type="text" name="paire" value="Example of value to show">
<input type="submit">
Run Code Online (Sandbox Code Playgroud)

预期结果将是:

要显示的值的示例

Den*_*ret 3

正如文档中的代码注释中提到的,FormData 反序列化只能通过 Post/x-www-form-urlencoded 请求(目前):

/// extract form data using serde
/// this handler gets called only if the content type is *x-www-form-urlencoded*
/// and the content of the request could be deserialized to a `FormData` struct
fn index(form: web::Form<FormData>) -> Result<String> {
    Ok(format!("Welcome {}!", form.username))
}
Run Code Online (Sandbox Code Playgroud)

所以你有两个解决方案:

1)将您的表单更改为 post/x-www-form-urlencoded 表单。这在您的示例中很容易,但在实际应用程序中并不总是可行

2)使用另一种形式的数据提取(还有其他几种提取器)