Home > Enterprise >  CSS file is not read properly using actix-web and maud
CSS file is not read properly using actix-web and maud

Time:02-12

CSS is not working via link rel attributes of maud with actix-web. Where I've made mistake(s)?

I think that position where I wrote link rel attributes is correct.

main.rs

use actix_files as fs;
use actix_web::{get, App, HttpServer, Result as AwResult};
use maud::{html, Markup};

#[get("/")]
async fn index() -> AwResult<Markup> {
    Ok(html! {
        head{
            link rel="stylesheet" href="/static/style.css"{};
        }
       title{"Help me"}

       p {"Blue text should be shown."}

    })
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(fs::Files::new("/static", ".").show_files_listing())
            .service(index)
    })
    .bind("0.0.0.0:80")?
    .run()
    .await?;
    Ok(())
}

style.css

p {
    color: blue;
    font-size: 50px;
}

enter image description here

enter image description here

enter image description here

CodePudding user response:

Looking at the documentation of actix_files::Files:

The first argument (mount_path) is the root URL at which the static files are served.

The second argument (serve_from) is the location on disk at which files are loaded.

You are using /static as first argument, so your files will be under http://0.0.0.0:80/static, all right.

But as second argument you set . that is the root of the project. This means that you are publishing the whole source of your project! For example, at http://0.0.0.0:80/static/src/main.rs (http://0.0.0.0:80/static/ is the mount point, ./src/main.rs is the local file) you will download the source of your binary, and you do not want that.

To fix your problem write instead:

fs::Files::new("/static", "./static")

The ./ in the second argument is optional, of course, but I like it because it reminds you that it is relative to the current working directory.

  • Related