我正在使用带有 express 和 passportjs 的 Node 来限制对位于私有(private)文件夹中的文件的访问。我已将我的代码减少到以下内容。 公共(public)静态文件夹中的所有内容都运行良好,但通过使用 staticMiddleware 定位私有(private)文件夹的路由返回 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);
我使用了以下似乎对其他人有用的引用资料,所以我一定遗漏了一些东西。 它不适用于我只显示位于私有(private)区域的内容的 404 响应。
Node.js module-specific static resources
NodeJS won't serve static files, even when using express.static
Redirecting to a static file in express.js
我可以发誓我以前有这个工作,也许它在新版本的某些东西中被破坏了。
- Node 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);
});
2014 年 11 月 29 日编辑
所以在有人发布了这个问题后,我回到这个答案,发现即使我提到了 passportjs,我也从未展示过我是如何最终使用这个功能的。
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);
});
关于node.js - 在授权路由中使用 express.static 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11473399/