6

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?

1 Answer 1

10

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.