栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何保护Node.js中的公共动态文件夹

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何保护Node.js中的公共动态文件夹

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

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

您有两种选择。最简单的方法是让Express 在公共中间件 之前 通过路由器路由请求,从而使您可以截获请求:

var express = require('express');var http = require('http');var path = require('path');var app = express();// use app.router before express.staticapp.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 filehttp://localhost:3000/protected/file.txt # You are not allowed!

这种方法的问题在于,在提供静态文件之前,请求必须一直通过应用程序的路由器进行处理,虽然效率不高,但可以满足您的需求(您需要采取一些措施)测量并自己找出)。


另一个选择是在中间件链中插入一个基本功能相同的小功能,但不需要在整个应用路由器中运行:

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 functionvar 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是否与您传入的正则表达式匹配。它运行检查以查看用户是否可以访问该文件。

结果:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373071.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号