【发布时间】:2013-06-05 21:01:17
【问题描述】:
现在,任何静态 html 都将使用
按原样(about.html、work.html 等)获取服务器app.use express.static("#{__dirname}/app")
我如何告诉它只用“about”返回相同的文件?
【问题讨论】:
现在,任何静态 html 都将使用
按原样(about.html、work.html 等)获取服务器app.use express.static("#{__dirname}/app")
我如何告诉它只用“about”返回相同的文件?
【问题讨论】:
express.static 实际上来自 Connect,Express 就是在它上面构建的。如果您查看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' }));
【讨论】:
您可以使用 Express'res.sendfile。一个基本的例子:
app.get('/:file', function (req, res) {
var file = req.params.file;
res.sendfile('app/' + 文件 + '.html');
});
【讨论】: