Jos*_*e A 3 json rust fetch-api rust-rocket
很抱歉问这样一个基本问题,Stack Overflow 和 GitHub 上几乎没有相关信息。这一定是愚蠢的事情,但我不明白。
我正在尝试使用 Rocket 0.5 RC1 通过 JavaScript 发送fetch到 Rust post 端点。但我受到以下打击:
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.
Run Code Online (Sandbox Code Playgroud)
这是我的 main.rs 文件(省略了不相关的部分):
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.
Run Code Online (Sandbox Code Playgroud)
这是我的 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"] }
Run Code Online (Sandbox Code Playgroud)
这是我的结构:
#[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)
}
Run Code Online (Sandbox Code Playgroud)
这是令牌有效负载:
我尝试过无参数获取请求,并且成功了。
我认为该Form结构正在读取并正确解析,FavoriteInput因为它允许丢失/额外的字段。
我一定做错了什么愚蠢的事情。有任何想法吗?
您似乎是JSON从 JavaScript 发送,但需要Form服务器上的参数。
你需要改变input: Form<FavoriteInput>与input: Json<FavoriteInput>.
| 归档时间: |
|
| 查看次数: |
833 次 |
| 最近记录: |