4
votes

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

2
I think FormData deserialization is only possible with Post/x-www-form-urlencoded requests right now. See actix.rs/docs/extractors - Denys Séguret
@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

2 Answers

3
votes

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)

0
votes

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