Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch GET & POST requests from HTML page using actix-web

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

like image 472
Cliff Anger Avatar asked Oct 15 '22 12:10

Cliff Anger


1 Answers

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)

like image 104
Denys Séguret Avatar answered Oct 18 '22 23:10

Denys Séguret