I use Express (v3) on my backend and it also serves my static content, like this:
app.use(allowCrossDomain);
app.use(disableETag);
app.use(app.router);
app.use(express["static"](webRootDir));
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.set('view engine', 'html');
app.set('views', webRootDir);
app.engine("html", handlebarsEngine);
So, a request for "/customers.html" is served by the express.static middleware. However, requesting "/customers" does not work, because there is no "customers" file and there is no such dynamic content route either.
Of course, I could serve the file "customers.html" from the dynamic route by following the path explained in Serve Static Files on a Dynamic Route using Express.
However, I think it is an overkill, such sort of things should be simply configurable through the default file extension, but I just could not find how. Can anyone show me?
express static is based on serve-static so you pass in an options object with the extensions property set. For your example the following would work:
app.use(express.static(webRootDir, {'extensions': ['html']}));
This sets up express so that if a file is not found eg /customers it will try appending each of the extensions to the path, so in your case /customers.html
See the docs at https://github.com/expressjs/serve-static#serve-files-with-vanilla-nodejs-http-server
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