actix-web json 意外行为
actix-web json unexpected behavior
我正在研究 actix-web,运行 遇到了以下问题。
我有 2 个函数,一个函数接受 post 字符串请求和 returns 结构的 json,另一个函数接受结构的 json 和 returns 字符串。但是,采用 json 结构会出现错误 400。
结构代码
#[derive(Deserialize, Serialize)]
pub struct MyObj {
pub name: String,
}
函数
#[post("/simple")]
pub async fn simple(obj: String) -> impl Responder {
MyObj {
name: obj,
}
}
#[post("/simplerecv")]
pub async fn simplerrecv(_obj: web::Json<MyObj>) -> String {
println!("Inside simplerecv");
"Hello".to_owned()
}
Python 用于测试的代码
def simple():
# testing simple
data = "hello44444"
r1 = requests.post("http://127.0.0.1:8080/simple", data=json.dumps(data))
print(r1.status_code, type(r1.text), r1.text)
res = json.loads(r1.text)
r2 = requests.post("http://127.0.0.1:8080/simplerecv",
data=json.dumps(json.loads(r1.text)))
print(r2.status_code)
Python 代码的输出
200 {"名称":""hello44444""}
400
有些网络服务器不接受没有 Content-Type: application/json
的 JSON,actix-web 也是如此。
r2 = requests.post("http://127.0.0.1:8080/simplerecv",
headers={'Content-Type': 'application/json;charset=utf-8'},
data=json.dumps(json.loads(r1.text)))
我正在研究 actix-web,运行 遇到了以下问题。 我有 2 个函数,一个函数接受 post 字符串请求和 returns 结构的 json,另一个函数接受结构的 json 和 returns 字符串。但是,采用 json 结构会出现错误 400。
结构代码
#[derive(Deserialize, Serialize)]
pub struct MyObj {
pub name: String,
}
函数
#[post("/simple")]
pub async fn simple(obj: String) -> impl Responder {
MyObj {
name: obj,
}
}
#[post("/simplerecv")]
pub async fn simplerrecv(_obj: web::Json<MyObj>) -> String {
println!("Inside simplerecv");
"Hello".to_owned()
}
Python 用于测试的代码
def simple():
# testing simple
data = "hello44444"
r1 = requests.post("http://127.0.0.1:8080/simple", data=json.dumps(data))
print(r1.status_code, type(r1.text), r1.text)
res = json.loads(r1.text)
r2 = requests.post("http://127.0.0.1:8080/simplerecv",
data=json.dumps(json.loads(r1.text)))
print(r2.status_code)
Python 代码的输出
200
400
有些网络服务器不接受没有 Content-Type: application/json
的 JSON,actix-web 也是如此。
r2 = requests.post("http://127.0.0.1:8080/simplerecv",
headers={'Content-Type': 'application/json;charset=utf-8'},
data=json.dumps(json.loads(r1.text)))