如何保护nodejs中的公共dynamic文件夹

我在公共/ images / picture.jpg中显示与玉的图片,但我想保护一些图片或限制访问公用文件夹如何做?

project node_modules public images image.jpg javascripts stylesheets protected_folder* image_protected.jpg views 

注意:对于所有这些示例,我使用的应用程序结构如下所示:

 . ├── app.js └── public ├── protected │  └── file.txt <-- contains text "protected file" └── regular └── file.txt <-- contains text "regular file" 

你有几个select。 最简单的就是让Express在公共中间件之前通过你的路由器路由请求,允许你拦截请求:

 var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); // use app.router before express.static app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); function userIsAllowed(callback) { // this function would contain your logic, presumably asynchronous, // about whether or not the user is allowed to see files in the // protected directory; here, we'll use a default value of "false" callback(false); }; app.get('/', function(req, res, next) { res.end('Home page'); }); app.get('/protected/*', function(req, res, next) { userIsAllowed(function(allowed) { if (allowed) { next(); // call the next handler, which in this case is express.static } else { res.end('You are not allowed!'); } }); }); http.createServer(app).listen(3000, function(){ console.log('Express server listening on port 3000'); }); 

结果:

 http://localhost:3000/regular/file.txt # regular file http://localhost:3000/protected/file.txt # You are not allowed! 

这种方法的问题是请求必须通过你的应用程序的路由器,才能提供静态文件,这是不是很有效,但可能是你的需要(你需要采取一些测量和找出自己)。


另一个select是在中间件链中插入一个小function,它基本上是一样的,但是不需要运行整个应用程序路由器:

 var express = require('express'); var http = require('http'); var path = require('path'); function userIsAllowed(callback) { // this function would contain your logic, presumably asynchronous, // about whether or not the user is allowed to see files in the // protected directory; here, we'll use a default value of "false" callback(false); }; // This function returns a middleware function var protectPath = function(regex) { return function(req, res, next) { if (!regex.test(req.url)) { return next(); } userIsAllowed(function(allowed) { if (allowed) { next(); // send the request to the next handler, which is express.static } else { res.end('You are not allowed!'); } }); }; }; var app = express(); app.use(protectPath(/^\/protected\/.*$/)); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res, next) { res.end('Home page'); }); http.createServer(app).listen(3000, function(){ console.log('Express server listening on port 3000'); }); 

这基本上执行相同的逻辑,但不是通过整个应用程序路由器路由每个请求,而是在每个请求开始时运行一个小函数,检查请求的URL是否与您传递的正则expression式匹配。如果是,它会运行检查以查看用户是否可以访问该文件。

结果:

 http://localhost:3000/regular/file.txt # regular file http://localhost:3000/protected/file.txt # You are not allowed!