FAQ - Help and questions

How do I handle an HTML form post in axum and redirect afterwards?

#axum#forms#html#redirectpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Add the Form extractor with a struct that derives Deserialize, and return Redirect::to to send the browser to a result page. The 303 status makes the browser fetch the next page with GET, so reloading it does not post the form again. A wrong content type gives 415 and a missing field 422.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Form<T> reads an application/x-www-form-urlencoded body into T. After a successful post, answer with a redirect instead of a page (the "post, redirect, get" pattern), so that a reload or the back button cannot submit the form twice.

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::Form,
    http::{header, Request},
    response::{Html, Redirect},
    routing::get,
    Router,
};
use serde::Deserialize;
use tower::ServiceExt;

#[derive(Deserialize)]
struct Contact { name: String, message: String }

async fn show_form() -> Html<&'static str> {
    Html(r#"<form method="post" action="/contact"><input name="name"><textarea name="message"></textarea><button>Send</button></form>"#)
}

async fn submit(Form(c): Form<Contact>) -> Redirect {
    println!("received from {}: {}", c.name, c.message);
    Redirect::to("/thanks") // 303 See Other: a page reload does not post again
}

async fn thanks() -> &'static str { "thank you" }

#[tokio::main]
async fn main() {
    let app = Router::new().route("/contact", get(show_form).post(submit)).route("/thanks", get(thanks));
    let req = Request::post("/contact")
        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
        .body(Body::from("name=Ada+L&message=Hello%2C+%26+welcome")).unwrap();
    let res = app.clone().oneshot(req).await.unwrap();
    println!("{} Location: {:?}", res.status(), res.headers().get(header::LOCATION).unwrap());
    let req = Request::post("/contact").body(Body::from("name=Ada")).unwrap();
    let res = app.clone().oneshot(req).await.unwrap();
    let status = res.status();
    let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
    println!("{status} {}", String::from_utf8_lossy(&body));
    let req = Request::post("/contact").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from("name=Ada")).unwrap();
    let res = app.clone().oneshot(req).await.unwrap();
    let status = res.status();
    let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
    println!("{status} {}", String::from_utf8_lossy(&body));
}

Output (the first line comes from the handler itself):

text
received from Ada L: Hello, & welcome
303 See Other Location: "/thanks"
415 Unsupported Media Type Form requests must have `Content-Type: application/x-www-form-urlencoded`
422 Unprocessable Entity Failed to deserialize form body: missing field `message`
  • + and %2C, %26 in the encoded body were decoded: Ada+L became Ada L, and the message Hello%2C+%26+welcome became Hello, & welcome.
  • Redirect::to answers 303 See Other with a Location header.
  • Without the form content type the extractor answers 415; with the content type but a missing field it answers 422.

Common mistakes#

  • Returning the result page directly from the POST handler. A reload then asks the browser to post again.
  • Putting <input> fields in the HTML without a name attribute: the browser sends only named fields, so the struct field is reported missing.

Does Form handle file uploads?#

No. Uploads use multipart/form-data; see the thread on file uploads with Multipart.

Where is the input checked for length or format?#

Form only checks that the fields exist and have the right type. Check ranges and formats yourself, as in the thread on validating input.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet