Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to serve static html files from express without the extension?

Tags:

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 
like image 343
Akshat Jiwan Sharma Avatar asked Jun 03 '13 10:06

Akshat Jiwan Sharma


People also ask

Can Express serve static files?

Express offers a built-in middleware to serve your static files and modularizes content within a client-side directory in one line of code.

Could your node server serve clients an HTML web page without having access to any files justify your answer?

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.

Can Express serve static files such as images?

To serve static files such as images, CSS files, and JavaScript files, use the express.


2 Answers

you can just use extension option in express.static method .

app.use(express.static(path.join(__dirname, 'public'),{index:false,extensions:['html']})); 
like image 176
sandeep rajbhandari Avatar answered Sep 27 '22 21:09

sandeep rajbhandari


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)); 
like image 30
robertklep Avatar answered Sep 27 '22 21:09

robertklep