Axum使用with_state传递应用状态时出现MethodRouter类型不匹配错误的解决求助
Axum使用with_state传递应用状态时出现MethodRouter类型不匹配错误的解决求助
我正在开发一个Axum项目,使用with_state API时遇到了问题。我的目标是给Axum路由中的处理器传递应用状态(AppState),但一直收到下面的错误:
note: expected struct
MethodRouter<()>
found structMethodRouter<AppState>
下面是我的项目结构:
main.rs
#[tokio::main] async fn main() { if let Ok(db) = init_db().await { let state = state::app_state::AppState::new(db); let routes = routes::root::routes(); let router = Router::new().with_state(state).nest("/api", routes); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); } }
root.rs
pub fn routes() -> Router { Router::new().merge(user_routes()) }
routes/user.rs
pub fn routes() -> Router { Router::new().route("/auth/register", post(register_user)) }
handler/user.rs
pub async fn register_user(Json(payload): Json<User>, State(state): State<AppState>) -> impl IntoResponse { ... } #[derive(Clone)] pub struct AppState { db_conn: Database } impl AppState { pub fn new(db: Database) -> AppState { AppState { db_conn: db } } }
错误提示MethodRouter<()>和MethodRouter<AppState>类型不匹配,我怀疑问题可能出在路由的设置或者root.rs中的合并方式上。有没有解决这个问题的建议?
我已经尝试过with_state和nest的不同配置组合,但错误仍然存在!希望能得到一些有用的见解!
备注:内容来源于stack exchange,提问作者Sasha Zoria
相关产品推荐
相关产品推荐

