【发布时间】:2021-02-26 13:33:29
【问题描述】:
我正在尝试使用 Postman 向我的 Rust API 发出 POST 请求:
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_derive;
use rocket_contrib::json::{Json, JsonValue};
#[derive(Serialize, Deserialize)]
struct Response {
status: String,
}
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[post("/register", format = "json", data = "<register>")]
fn user_create(register: Json<Response>) -> Json<Response> {
Json(Response {
status: "works".to_string(),
})
}
fn main() {
rocket::ignite()
.mount("/", routes![index, user_create])
.launch();
}
Cargo.toml:
[package]
name = "hello-rocket"
version = "0.1.0"
authors = [""]
edition = "2018"
[dependencies]
rocket = "0.4.6"
serde = { version = "1.0", feature = ["derive"]}
serde_json = "1.0"
serde_derive = "1.0"
[dependencies.rocket_contrib]
version = "0.4.6"
default-features = false
features = ["json"]
我在 Postman 中配置了一个 Content-Type: application/json 标头,我的请求正文是 {"status": "running"}:
我得到了
Error: Couldn't parse JSON body: Error("EOF while parsing a value", line: 1, column: 0)
【问题讨论】:
-
这段代码似乎对我有用。仔细检查所有内容:正确的请求(POST /register)、正确的主机、最新版本,确保您的请求中没有任何奇怪的字节。如果这不起作用,请包括您的依赖项的版本和可重现的示例(火箭
.mount、.launch和所有)。 -
@kmdreko 我更新了我的 cargo 和 rustup 版本,并确保我所有的依赖项都是最新版本。我什至创建了一个新项目来测试它,但它仍然无法正常工作。
-
将您的完整代码和 cargo.toml 添加到您的帖子中
-
这不是 Rust 问题:
curl -X POST --header 'Content-Type: application/json' --data '{"status": "running"}' http://localhost:8000/register==>{"status":"works"}。你一定是在滥用邮递员。 -
你也有警告。当您尝试调试问题时,始终解决所有警告!
warning: unused manifest key: dependencies.serde.feature
标签: json rust postman rust-rocket