Post Rocket 路由转发(Rust)

Post Rocket route is forwarded (Rust)

很抱歉问这样一个基本问题,Stack Overflow 和 GitHub 中几乎没有关于此的信息。这一定很愚蠢,但我不明白。

我正在尝试通过 JavaScript 的 fetch 发送到带有 Rocket 0.5 RC1 的 Rust post 端点。但我受到了打击:

No matching routes for POST /api/favorites application/json.

这是完整的日志:

    POST /api/favorites application/json: 
    Matched: (post_favorites) POST /api/favorites
    `Form < FavoriteInput >` data guard is forwarding.
    Outcome: Forward
    No matching routes for POST /api/favorites application/json.  
    No 404 catcher registered. Using Rocket default.
    Response succeeded.

这是我的 main.rs 文件(省略无关部分):

#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let cors = CorsOptions::default()
        .allowed_origins(AllowedOrigins::all())
        .allowed_methods(
            vec![Method::Get, Method::Post, Method::Patch]
                .into_iter()
                .map(From::from)
                .collect(),
        )
        .allow_credentials(true)
        .to_cors()?;

    rocket::build()
        .mount("/api", routes![index, upload::upload, post_favorites])
        .attach(cors)
        .launch()
        .await?;

    Ok(())
}

#[post("/favorites", data = "<input>")]
async fn post_favorites(input: Form<FavoriteInput>) -> Json<Favorite> {
    let doc = input.into_inner();
    let fav = Favorite::new(doc.token_id, doc.name);
    let collection = db().await.unwrap().collection::<Favorite>("favorites");
    collection.insert_one(&fav, None).await.unwrap();
    Json(fav)
}

这是我的 cargo.toml:


[dependencies]
rocket = {version ="0.5.0-rc.1", features=["json"]}
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
reqwest = {version = "0.11.6", features = ["json"] }
serde= {version = "1.0.117", features= ["derive"]}
mongodb = "2.1.0"
rand = "0.8.4"
uuid = {version = "0.8", features = ["serde", "v4"] }

这是我的结构:

#[path = "./paste.rs"]
mod paste;

#[derive(Serialize, Deserialize, Debug)]
pub struct Favorite {
    pub id: String,
    pub token_id: String,
    pub name: String,
}

impl Favorite {
    pub fn new(token_id: String, name: String) -> Favorite {
        let id = Uuid::new_v4().to_string();
        let fav = Favorite { token_id, name, id };

        fav
    }
}

#[derive(FromForm, Serialize, Deserialize, Debug)]
pub struct FavoriteInput {
    pub token_id: String,
    pub name: String,
}

这是令牌负载:

我试过使用无参数获取请求,它们成功了。

我认为 Form 结构正在读取并正确解析 FavoriteInput,因为它允许 missing/extra 字段。

一定是我做错了什么傻事。有什么想法吗?

您似乎是从 JavaScript 发送 JSON,但期望服务器上有 Form 个参数。

您需要将 input: Form<FavoriteInput> 更改为 input: Json<FavoriteInput>