5

I am getting an error message when submitting HTML form in order to catch the requested details inside FORM (I am using actix-web).

When I submit the FORM, I am getting this error:

Content type error

The code used:

#[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()))
))

HTML form used:

<form action="http://127.0.0.1:8080/" method="get">
<input type="text" name="paire" value="Example of value to show">
<input type="submit">

The expected result will be:

Example of value to show

Cliff Anger
  • 195
  • 2
  • 11
  • 1
    I think FormData deserialization is only possible with Post/x-www-form-urlencoded requests right now. See https://actix.rs/docs/extractors/ – Denys Séguret Jul 16 '19 at 19:37
  • @DenysSéguret Thank you ! I got it solved using POST method + enctype (x-www-form-urlencoded). You can make a comment so I can accept your answer ;) – Cliff Anger Jul 16 '19 at 19:44

2 Answers2

3

As is mentioned in code comments in the documentation, FormData deserialization is only possible with Post/x-www-form-urlencoded requests (for the moment):

/// 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))
}

So you have two solutions:

1) change your form to a post/x-www-form-urlencoded one. This is easy in your example but it's not always possible in real applications

2) use another form of data extraction (there are several other extractors)

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

I had this problem too, and solved it by changing from web::Form to web::Query.

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

fn get_user_detail_as_plaintext(form: web::Query<FormData>) -> Result<String> {
    Ok(format!("User: {}!", form.username))
}
neoneye
  • 50,398
  • 25
  • 166
  • 151