Node.js: get css file with html rendering

How can I add a CSS file to my HTML visualization file in Node.js?

That's what I'm doing:

<link rel="stylesheet" type="text/css" href="./general.css" /> 

And here is the error when I go to localhost: 8333 / general.css:

 Cannot GET /general.css 

My script rendering module looks like this:

 app.set('views', __dirname); app.engine('html', engines.mustache); app.set('view engine', 'html'); 

How can I do it?

+4
source share
1 answer

You can use static Express middleware to serve static files such as JS and CSS:

 app.use(express.static()); 

This will by default try to find static files in ./public (compared to the script from which you configure the middleware):

 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" /> 

Medium- ./public/css/general.css software will find and (if found) serve ./public/css/general.css .

If you want to establish where your CSS files are located in the same directory as your script application, you can specify middleware where to search for files by passing the directory as the first argument:

 app.use(express.static(__dirname)); 
+7
source

All Articles