在授权的路线中使用express.static中间件

我正在使用express和passportjs节点来限制对位于私人文件夹中的文件的访问。 我已经减less了我的代码到以下。 公共静态文件夹中的所有内容都很好用,但是通过使用staticMiddleware来定位私有文件夹的路由将返回404错误。

var express = require('express') , util = require('util'); var app = express.createServer(); var staticMiddleware = express.static(__dirname + '/private'); app.configure(function() { app.use(app.router); app.use(express.logger('dev')); app.use('/public',express.static(__dirname + '/public')); }); app.get('/private/:file', function(req, res, next){ console.log('about to send restricted file '+ req.params.file); staticMiddleware(req, res, next); }); app.listen(16000); 

我正在使用下面的引用,似乎为别人工作,所以我必须失去一些东西。 这对我而言不起作用,只显示位于私人区域的内容的404个响应。

Node.js模块特有的静态资源

即使使用express.static,NodeJS也不会提供静态文件

redirect到express.js中的静态文件

我可以发誓,我有这个工作之前,也许它被打破了一个新的东西版本。

  • 节点v0.8.1
  • npm 1.1.12
  • express@2.5.11
  • connect@1.9.2

她一直盯着我

 app.get('/private/:file', function(req, res, next){ console.log('about to send restricted file '+ req.params.file); req.url = req.url.replace(/^\/private/, '') staticMiddleware(req, res, next); }); 

编辑11-29-2014

所以有人发布到这个问题后,我回到这个答案,发现即使我提到passportjs我从来没有展示我如何结束了使用这个function。

 var staticMiddlewarePrivate = express['static'](__dirname + '/private'); app.get('/private/*/:file', auth.ensureAuthenticated, function(req, res, next){ console.log('**** Private ****'); req.url = req.url.replace(/^\/private/, ''); staticMiddlewarePrivate(req, res, next); }); 

你也可以添加express.static(__dirname + '/private'); 到你的app.config。

 app.configure(function() { app.use(app.router); app.use(express.logger('dev')); app.use('/public',express.static(__dirname + '/public')); app.use('/private',express.static(__dirname + '/private')); }); 

privatepath中间件将随时以private开始执行。