How can I include a CSS file in my HTML file with a HTML render in Node.js?
Here's what I do:
<link rel="stylesheet" type="text/css" href="./general.css" />
And then is the error when I'm going to localhost:8333/general.css:
Cannot GET /general.css
My module renderer script is the following:
app.set('views', __dirname);
app.engine('html', engines.mustache);
app.set('view engine', 'html');
How should I do it?
You can to use Express' static middleware to serve static files like (client-side) JS and CSS:
app.use(express.static());
That will, by default, try and find static files in ./public
(relative to the script you configure the middleware from):
yourproject/app.js <-- if configured here
yourproject/public/ <-- it will look here
If you use this in your HTML/template:
<link rel="stylesheet" type="text/css" href="/css/general.css" />
The middleware will find and (if found) serve ./public/css/general.css
.
If you want a setup where your CSS files are in the same directory as your application script, you can tell the middleware where to look for files by passing a directory as first argument:
app.use(express.static(__dirname));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With