rustactix-web

Always getting 404 response when using service with scope in actix-web


I am writing an application using Actix Web and when configuring the routes i wanted to use scopes. The problem is that I can't seem to get them working like they should according to the documentation. Even though everything seems correct I always get a 404 response.

#[get("/")]
async fn show_users() -> HttpResponse {
    HttpResponse::Ok().finish()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
        .service(show_users)
        .service(web::scope("/users").service(show_users))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

I can access the function through localhost:8080 but not localhost:8080/users

Isn't this basically the same as the first code example here?

https://actix.rs/docs/application#using-an-application-scope-to-compose-applications


Solution

  • The change that needs to be made is removing the / from the get.

    Like this:

    #[get("")]
    async fn show_users() -> HttpResponse {
        HttpResponse::Ok().finish()
    }
    
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        HttpServer::new(|| {
            App::new()
            .service(show_users)
            .service(web::scope("/users").service(show_users))
        })
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
    }