rust - 从 "reqwest"crate rust 发出 post 请求时请求正文为空

我正在尝试使用 reqwest crate of rust 发出发布请求。这是 cargo.toml 的片段

[dependencies]
tokio = { version = "0.2", features = ["full"] }
reqwest = { version = "0.10", features = ["json"] }

这是我向简单服务器发出请求的代码片段。

use reqwest::{Response, StatusCode};
use serde_json::{json, Value};

#[tokio::main]
async fn main() ->  Result< (),  reqwest::Error>  {

    let map1 = json!({
        "abc":"abc",
        "efg":"efg"
    });

    let body: Value = reqwest::Client::new()
    .post("http://localhost:4000/hello")
    .json(&map1)
    .send()
    .await?
    .json()
    .await?;

    println!("Data is : {:?}", body);

    Ok(())
}

使用简单服务器箱编写的代码片段如下:

use simple_server::{Server, StatusCode};

fn main() {
    let server = Server::new(|req, mut response| {

        println!(
            "Request received {} {} {:?}",
            req.method(),
            req.uri(),
            &req.body()
        );

        match (req.method().as_str(), req.uri().path()) {
            ("GET", "/") => Ok(response.body(format!("Get request").into_bytes())?),

            ("POST", "/hello") => Ok(response.body(format!("Post request").into_bytes())?),

            (_, _) => {
                response.status(StatusCode::NOT_FOUND);
                Ok(response.body(String::from("Not Found").into_bytes())?)
            }
        }
    });

    server.listen("127.0.0.1", "4000");
}

我得到的输出是:

Request received POST /hello []

所需的输出是字节向量数组,但我收到的是一个空向量数组。

我已经尝试过的解决方案是:

  • 使用 Postman 向同一台服务器发出发布请求并且工作正常。
  • 使用相同的 reqwest 代码向任何其他服务器(如 hyper、actix 等)发出发布请求,并且工作正常。
  • 发送一个简单的正文作为 post 请求的正文(无 JSON)。但同样的问题出现了。

所以我认为问题一定出在这个简单的服务器机箱上。 每一个有值(value)的建议都会得到鼓励。

最佳答案

use reqwest::{Response, StatusCode};
use serde_json::{json, Value};

#[tokio::main]
async fn main() ->  Result<String>  {

 let map1 = json!({
    "abc":"abc",
    "efg":"efg"
 });

 let body: Value = reqwest::Client::new()
 .post("http://localhost:4000/hello")
 .json(&map1)
 .send()
 .await?
 .json()
 .await?;

 println!("Data is : {:?}", body);
 let resp = serde_json::to_string(&body).unwrap();
    Ok(resp)

 }

关于rust - 从 "reqwest"crate rust 发出 post 请求时请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61321173/

相关文章:

python - 管道中的第二个 `ParallelRunStep` 在启动时超时

ruby-on-rails - 指定环境时 Webpacker 不替换 "process.env"变

javascript - 数据切换选项卡不下载传单 map

r - 图形窗口在 `kml` 包中无法正常工作

uwp - 如何支持使用 Windows Cloud Sync Engine API 进行删除?

windows - 如何使用 ssh 将 git push 到远程 Windows 机器

pyspark - Spark Structured Streaming时DataFrame中的字符

mysql - SQL:如果*条件*在另一行,则更新一行

python - 使用 Python Selenium 下载文件

amazon-web-services - 注册到 AWS Chime session 通知