Unable to get response body in axum

Unable to get response body in axum middleware.

let res = next.run(req).await;
println("{:?}", res.body().is_empty());

is_empty is not found. But in example its showing.

You need to investigate what the type of res actually is. It is probably a BoxBody, which does not have an is_empty() method defined on it. If you want to know the size of data behind a BoxBody, you should be able to use res.body().size_hint().

Some types, like String, do have is_empty() defined. For example, this will work:

let res: http::Response<String> = http::Response::default();
assert!(res.body().is_empty());

The middleware code examples you have seen may have been working on Strings or something similar.

Thanks but if we skip the is_empty part.
Then can we get response body as a string before send the payload?

Edit

You are generating new response where I wants to know the response that already has been build & ready to dump. I wants to know that response & get the response body.

You are generating new response where I wants to know the response that already has been build & ready to dump. I wants to know that response & get the response body.

Yes, I was just giving an example of something that works with is_empty().

Assuming you are working with a BoxBody, something like this should work:

let mut res = next.run(req).await;

match res.data().await {
    Some(data) => {
        match data {
            Ok(bytes) => println!("{:#?}", bytes),
            Err(e) => println!("Error getting data from body: {}", e),
        }
    }
    None => {
        println!("Empty response body");
    }
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.