vignesh waran vignesh waran - 6 months ago 67
Node.js Question

Express js is not serving static files

I am new to express js.I think this is a newbie problem.express js is not serving static files

var express = require('express');
express()
.set('view engine','ejs')
.use(express.static('public'))
.get('/',function(req,res){
res.render('index');
})
.listen(3000);


Error
Project Structure

Answer

I think you need to use:

.use('/public', express.static('public'))

The first public is what you use as a prefix in your url. The second public is your physical folder in your file system.

Another option would be not to use /public/* in your urls.

From the docs:

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

app.use('/static', express.static('public'));

Now, you can load the files that are in the public directory from the /static path prefix.