我正在学习用rust写一个API来更新一些记录。我定义了一个rust(v1.69.0
)rocket API如下:
#[macro_use] extern crate rocket;
use rocket::{serde::json::Json, response::content};
use rust_wheel::common::util::model_convert::box_rest_response;
use rocket::serde::Deserialize;
use rocket::serde::Serialize;
#[put("/test", data = "<request>")]
pub fn flush_render_result(
request: Json<RenderResultRequest>
) -> content::RawJson<String> {
let req = request;
return box_rest_response("ok");
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![flush_render_result])
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct RenderResultRequest {
pub gen_status: i32,
pub id: i64,
}
这就是Cargo.toml
:
[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"
[dependencies]
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
rocket = { version = "0.5.0-rc.2", features = ["json"]}
rust_wheel = { git = "https://github.com/jiangxiaoqiang/rust_wheel.git", branch = "diesel2.0" }
这是Rocket.toml
:
[release]
workers = 5
log_level = "normal"
keep_alive = 5
port = 11016
[debug]
port = 11016
当我在macOS 13.2终端中使用命令请求API时:
> curl -X PUT http://127.0.0.1:11016/test -H "Content-Type: application/json" -H "x-access-token:1" -H "app-id:1" -H "user-id:1" -H "x-request-id:1" -H "device-id:1" -d "{
"id": 1,
"gen_status": 1
}"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>400 Bad Request</title>
</head>
<body align="center">
<div role="main" align="center">
<h1>400: Bad Request</h1>
<p>The request could not be understood by the server due to malformed syntax.</p>
<hr />
</div>
<div role="contentinfo" align="center">
<small>Rocket</small>
</div>
</body>
</html>%
为什么会发生这样的事呢?我该怎么做才能解决这个问题?我已经为键添加了“”,为什么还告诉我这个错误?服务器日志如下所示:
📬 Routes:
>> (flush_render_result) PUT /test
📡 Fairings:
>> Shield (liftoff, response, singleton)
🛡️ Shield:
>> X-Content-Type-Options: nosniff
>> Permissions-Policy: interest-cohort=()
>> X-Frame-Options: SAMEORIGIN
🚀 Rocket has launched from http://127.0.0.1:11016
PUT /test application/json:
>> Matched: (flush_render_result) PUT /test
>> Data guard `Json < RenderResultRequest >` failed: Parse("{\n id: 1,\n gen_status: 1\n}", Error("key must be a string", line: 2, column: 5)).
>> Outcome: Failure
>> No 400 catcher registered. Using Rocket default.
>> Response succeeded.
我试过删除空间,还是不行:
curl -X PUT http://127.0.0.1:8000/cv/gen/v1/result -H "Content-Type: application/json" -H "x-access-token:1" -H "app-id:1" -H "user-id:1" -H "x-request-id:1" -H "device-id:1" -d "{"id": 1,"gen_status": 1}"
1条答案
按热度按时间vsmadaxz1#
您未能在curl调用中正确转义
"
,因此shell使用了它们,导致有效负载为而不是有效的JSON
请注意键的引号中的差异。
要解决这个问题,你可以在json中使用转义引号(
\"
)来调用curl,或者像这样使用不同的外引号: