1

现在,任何静态 html 都将使用原样(about.html、work.html 等)获取服务器

app.use express.static("#{__dirname}/app")

我如何告诉它只用“about”返回相同的文件?

4

2 回答 2

3

express.static实际上来自Connect, Express 是在其上构建的。如果您查看静态中间件的源代码,您会发现它相对简单,因为真正的逻辑已被抽象到发送模块中。

内置的静态中间件无法完成您想要完成的工作,但将其调整为您自己的就足够简单了:

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' }));
于 2013-06-05T21:31:55.250 回答
2

您可以使用 Express' res.sendfile。一个基本的例子:

app.get('/:file', function (req, res) {
    var file = req.params.file;

    res.sendfile('app/' + 文件 + '.html');

});
于 2013-06-05T21:27:05.430 回答