Can't solve the problem why the auth handler says trait bound is not satisfied!


use axum::{
    response::{Html, IntoResponse},
    routing::{get, post},
    Extension, Form, Router,
};
use mongodb::{bson::doc, options::ClientOptions, Client, Collection, Database};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    email: String,
    password: String,
}

#[tokio::main]
async fn main() {
    let client_options = ClientOptions::parse("mongodb://localhost:27017")
        .await
        .unwrap();
    let mydb: Database = Client::with_options(client_options)
        .unwrap()
        .database("mydb");
    let app = Router::new()
        .route("/", get(root))
        .route("/auth", post(auth))
        .with_state(mydb);
    let tcp = TcpListener::bind("localhost:8000").await.unwrap();
    axum::serve(tcp, app.into_make_service()).await.unwrap();
}
async fn root() -> impl IntoResponse {
    let file_content = fs::read_to_string("index.html").unwrap_or_default();
    Html(file_content)
}
async fn auth(Form(body): Form<User>, mydb: Extension<Database>) -> String{
    let users: Collection<User> = mydb.collection("users");
    let _something = users.find_one(doc! {"email": body.email}, None).await;
	match _something {
		Ok(_value)=> "OK".to_string(),
		Err(_e)=> "NOT_OK".to_string(),
	}
}

What versions of dependencies do you use? It's hard to help without reproducible example, and this code by itself is not reproducible (different Axum/Tokio/etc. versions can change the picture a lot).


name = "hello-axum"

version = "0.1.0"

edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

axum = "0.7.4"

tokio = { version = "1.35.1", features = ["macros", "rt-multi-thread"] }

serde = { version = "1.0.196", features = ["derive"] }

serde_json = "1.0.113"

mongodb = {version = "*", features = ["tokio-runtime"]}```

According to documentation:

Since parsing form data might require consuming the request body, the Form extractor must be last if there are multiple extractors in a handler.

After switching the order of arguments for auth, i.e. defining it as async fn auth(mydb: Extension<Database>, Form(body): Form<User>) -> String, the code compiles.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.