[英]How can I respond to a POST request containing JSON data with Rocket?
我正在尝试使用Rocket crate创建一个后端:
fn main() {
rocket::ignite().mount("/", routes![helloPost]).launch();
}
#[derive(Debug, PartialEq, Eq, RustcEncodable, FromForm)]
struct User {
id: i64,
USR_Email: String,
USR_Password: String,
USR_Enabled: i32,
USR_MAC_Address: String
}
#[post("/", data = "<user_input>")]
fn helloPost(user_input: Form<User>) -> String {
println!("print test {}", user_input);
}
当我运行cargo run
一切正常,但是,当我向邮递员发送 POST 请求进行测试时,出现此错误:
POST /:
=> Matched: POST / (helloPost)
=> Warning: Form data does not have form content type.
=> Outcome: Forward
=> Error: No matching routes for POST /.
=> Warning: Responding with 404 Not Found catcher.
=> Response succeeded.
我已将标头内容类型设置为 JSON 并使用其他有效语言,但使用 Rocket 我无法使其正常工作。
这是我的 JSON 正文:
{
"USR_Email": "test@test.it",
"USR_Password": "500rockets",
"USR_Enabled": 0,
"USR_MAC_Address": "test test"
}
如何解决这个问题?
基本上逐字改编自Rocket_contrib 示例。
货物.toml:
<snip>
[dependencies]
rocket = "0.4.2"
rocket_contrib = "0.4.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
src/main.rs:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use rocket_contrib::json::Json;
use serde::Deserialize;
#[derive(Debug, PartialEq, Eq, Deserialize)]
struct User {
id: i64,
USR_Email: String,
USR_Password: String,
USR_Enabled: i32,
USR_MAC_Address: String
}
#[post("/", format = "json", data = "<user_input>")]
fn helloPost(user_input: Json<User>) -> String {
format!("print test {:?}", user_input)
}
fn main() {
rocket::ignite().mount("/hello", routes![helloPost]).launch();
}
一些注意事项:
Json
代替Form
format = "json"
添加到您的路线serde
Deserialize
而不是RustcEncodable
。 Serde 早已取代 rustc_serialize 作为 Rust的序列化解决方案,这也是 Rocket_contrib 所使用的。用 curl 测试:
$ curl -H 'Content-Type: application/json' \
--data '{"id": 123, "USR_Email": "abc@example.com", "USR_Password": "hunter2", "USR_Enabled": 1, "USR_MAC_Address": "ff:ff"}' \
http://localhost:8000/hello
print test Json(User { id: 123, USR_Email: "abc@example.com", USR_Password: "hunter2", USR_Enabled: 1, USR_MAC_Address: "ff:ff" })
请注意,您的User
中的每个字段都必须以 JSON 格式存在,否则将引发400 Bad Request
。 您可能希望将Option<>
用于其中一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.