How to set Express route alias to html file?

2020-08-09 11:40发布

问题:

I'm trying to serve some static file with a nicer url endpoints.

For example, /home will serve /public/home.html.

I can probably use res.sendfile() in the route config, but sendfile will not cache the file output in production mode so I am not too sure if this is a good solution.

How do I set routes to act like an alias to a html file?

回答1:

Try this.

var express = require('express');
var app =express.createServer();
// ------
app.get('/home', function(req,res){
 res.sendfile(__dirname + '/public/home.html');
}); 


回答2:

There's a module called node-static that provides cacheing functionality. You also might be able to just use symlinks. You might be better served with nginx's try_files or another non-node.js reverse proxy for this functionality.

For a while, there was a staticCache middleware built into express that would do the cacheing. It was removed from connect in January 2014.Here's the github issue where TJ explains staticCache being deprecated.