Currently, I am tackling a beginner node.js server project. While I have successfully managed to render dynamic HTML using ejs templates, I seem to be facing difficulties when it comes to linking CSS styling to these templates.
In an effort to address this issue, I created a public directory to store assets such as images and external CSS files. Subsequently, I attempted to link the static contents to Express using:
app.use(express.static('/public', __dirname + '/public'));
While the images (.jpg) stored in my public folder are being rendered correctly, the CSS file within that same directory is not displaying properly.
File Structure:
node_modules
models
views
public > app.css, hero.jpg
server.js
package.json
Below is a snippet of my Express app configuration from server.js:
const express = require('express');
const app = express();
const ejs = require('ejs');
app.use('/public', express.static(__dirname + '/public');
app.set("view engine", "ejs");
app.set('views',__dirname+'/views');
app.get('/', (req,res) =>{
res.render('home',{
title: "HomePage",
date : new Date().getFullYear()
});
});
app.listen(3000);
Within the home.ejs file, the head section includes:
<head>
<meta charset = "utf-8">
<title> My Website <%= title %> </title>
<link rel="stylesheet" href="/app.css" type="text/stylesheet">
</head>
Despite my expectations for the app.css file to load successfully based on the code above, it seems that it's not functioning as intended within the home.ejs file.