如何让node.js返回没有文件扩展名的页面?

现在,任何静态html将得到服务器(about.html,work.html等)使用

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

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

express.static实际上来自Connect ,Express在其上构build。 如果你看一下静态中间件的来源 ,你会发现它比较简单,因为真正的逻辑已经被抽象到发送模块。

烘焙的静态中间件不能完成你想要完成的任务,但是将它简化成你自己的:

 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' })); 

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

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

     res.sendfile('app /'+ file +'.html');

 });