【发布时间】:2022-01-23 13:46:29
【问题描述】:
很抱歉问了这么一个基本问题,在 Stack Overflow 和 GitHub 上几乎没有这方面的信息。这一定很愚蠢,但我不明白。
我正在尝试通过 JavaScript 的 fetch 发送到带有 Rocket 0.5 RC1 的 Rust 发布端点。但我受到了打击:
没有与 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,
}
这是令牌有效负载:
我已经尝试过无参数的 get 请求,它们成功了。
我认为 Form 结构正在读取并正确解析 FavoriteInput,因为它允许丢失/额外的字段。
一定是我做错了什么愚蠢的事情。有什么想法吗?
【问题讨论】:
标签: json rust fetch-api rust-rocket