htmlcssexpress

How to link CSS to html in an express project?


I have an Express.js project which looks like this:

In routes/index.js I can display my html file like this:

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/../views/authentication.html'));
});

But the file is displayed without its style contained in authentication.css. However, authentication.css is linked to authentication.html :

<head>
    <meta charset="utf-8">
    <link rel = "stylesheet" href = "authentication.css">
</head>

I tried to move my .css to the public/stylesheets folder and change the <link> tag to point to the new location but it didn't worked.

What am I supposed to do to apply my CSS files to the corresponding html files?


Solution

  • So I found some sort of solution thanks to this post : https://stackoverflow.com/a/17911882/5016201 .

    I just added this line in app.js:

    app.use(express.static(__dirname + 'views'));
    

    It displays my html + css files correctly, I don't know if it is a good practice but it is good enough for what I am doing.