Search code examples
http-redirectrustactix-web

How to redirect to different route (and method: POST -> GET) in Actix-Web?


In the following code, I want to redirect from the index endpoint to the hello endpoint.

#[get("/hello")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/")]
async fn index(req_body: String) -> impl Responder {
    //Logic
    //Redirect to route /hello 
}

I tried to use explicitly Redirect::to but that does a POST request instead of a GET.

#[post("/")]
async fn index(req_body: String) -> impl Responder {
    //Logic
    Redirect::to("/hello").permanent()
}
actix_web::middleware::logger] 127.0.0.1 "POST /index HTTP/1.1
actix_web::middleware::logger] 127.0.0.1 "POST /hello HTTP/1.1

Got anyone any solutions or different approaches to this problem?


Solution

  • Sounds like you want a 303 See Other redirect. From the MDN docs:

    Method handling

    GET methods unchanged. Others changed to GET (body lost).

    Typical use case

    Used to redirect after a PUT or a POST, so that refreshing the result page doesn't re-trigger the operation.

    You can do this in Actix-Web with the .see_other() chain method:

    Redirect::to("/hello").see_other()