I would like to serve an html file without specifying it's extension. Is there any way I can do this without defining a route? For instance instead of
/helloworld.html
I would like to do just
/helloworld
Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.
nodejs does NOT serve any files/URLs by default. You have to start a server and then install some code (your own code or one of the many libraries built for doing this) for handling whatever paths/filenames you want your server to respond to.
To serve static files such as images, CSS files, and JavaScript files, use the express.
you can just use extension option in express.static method .
app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']}));
A quick'n'dirty solution is to attach .html
to requests that don't have a period in them and for which an HTML-file exists in the public directory:
var fs = require('fs'); var publicdir = __dirname + '/public'; app.use(function(req, res, next) { if (req.path.indexOf('.') === -1) { var file = publicdir + req.path + '.html'; fs.exists(file, function(exists) { if (exists) req.url += '.html'; next(); }); } else next(); }); app.use(express.static(publicdir));
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