2

我正在尝试使用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"
}

如何解决这个问题?

4

1 回答 1

4

基本上逐字改编自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"到您的路线
  • 使用Deserializefromserde而不是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<>其中的一些。

于 2020-01-29T12:44:11.557 回答