How can I get the body out of a `HttpRequest` in `actix_web` crate?

I have two following functions:

async fn jumped(req: web::Bytes) -> impl Responder {
    let expected_body_string = String::from_utf8(req.to_vec()).unwrap();
    println!("{:?}", expected_body_string);

async fn to_jump() -> impl Responder {
    let generated_body = String::from("random generated body string");
        .append_header((header::LOCATION, "/my_path/my_path_next"))

When I open the url /my_path, the function to_jump start to work, a String is generated and then inserted to the HttpBuilder's body. Next the the url jump to /my_path/my_path_next, to which I expected the body generated before will be transported, the function jumped should print out random generated body string, but nothing was printed out.
What am I doing wrong?

that's not how HTTP redirect work. the response with a "Location" header is sent to the client browser, the browser sees the header, and make another request to the new url.

1 Like

I am confused. You hit the "/my_path" path, but you were expecting to see the code from the jumped handler to run?


Ah, I missed that part. Now it makes sense.

1 Like

Is there a easy way I can redirect the url, at the same time translated some information to the new url?

From the docs:

use actix_web::{web::Redirect, Responder};

async fn handler() -> impl Responder {
    // sends a permanent (308) redirect to
1 Like

the redirected request is made by the client, so usual techniques to store information on the client side can be used. for example, you can use cookie or encode the information into the redirected url. but that's pretty much what you can do with a redirect.

however, if you are not required to redirect the client to a new url, you can do it with a server middleware.

for example, you can create a regular expression based rewrite (different from redirect) engine, which is essentially an reverse proxy under the hood.

1 Like

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.