首页 > 解决方案 > 从 "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 []

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

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

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

标签: rustrust-cargorust-tokioreqwest

解决方案


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)

 }

推荐阅读