现在,任何静态html都将使用
按原样获取服务器(about.html,work.html等)app.use express.static("#{__dirname}/app")
如何告诉它仅使用“about”返回相同的文件?
答案 0 :(得分:3)
express.static
实际上来自构建Express的Connect。如果你看the source of the static middleware,你会发现它相对简单,因为真实的逻辑被抽象出send模块。
内置的静态中间件无法完成您想要完成的任务,但将其调整为您自己的内容非常简单:
var send = require('./node_modules/express/node_modules/send') // grab the npm-installed send module that comes with express
, utils = require('.node_modules/express/node_modules/connect/lib/utils') // ...and connect's utils
, parse = utils.parseUrl
, url = require('url');
function customStatic(root, options){
options = options || {};
// root required
if (!root) throw new Error('static() root path required');
// note: I've stripped out directory redirection
// (ie, redirecting from /somefolder to /somefolder/)
// because appending an extension logically makes that code unreachable
return function(req, res, next) {
if ('GET' != req.method && 'HEAD' != req.method) return next();
var path = parse(req).pathname
, filename = pathname.substr(pathname.lastIndexOf('/')); // the part of the URL after the last slash, excluding the query string
// and finally, the reason we're here: if the filename has no extension, append one
if (options.defaultExtension && filename.indexOf('.') == -1) path += '.' + options.defaultExtension;
var pause = utils.pause(req);
function resume() {
next();
pause.resume();
}
function error(err) {
if (404 == err.status) return resume();
next(err);
}
send(req, path)
.maxage(options.maxAge || 0)
.root(root)
.index(options.index || 'index.html')
.hidden(options.hidden)
.on('error', error)
.pipe(res);
};
};
然后像Connect的静态模块一样使用它:
app.use(customStatic(__dirname + '/app', { defaultExtension: 'html' }));
答案 1 :(得分:2)
您可以使用Express'res.sendfile
。一个基本的例子:
app.get('/:file', function (req, res) { var file = req.params.file; res.sendfile('app/' + file + '.html'); });