简体   繁体   English

ExpressJS限制对公共文件的访问

[英]ExpressJS restricting access to public files

Is there a way to hide files that are being served by the Node server? 有没有办法隐藏节点服务器正在提供的文件? I have tried to reroute certain files and directories, but nothing is working in Express 4.X. 我试图重新路由某些文件和目录,但是Express 4.X中没有任何工作。 I have also tried to send 4XX HTTP responses when certain files are requested, but this only works for directory paths. 当请求某些文件时,我也尝试发送4XX HTTP响应,但这仅适用于目录路径。 No matter what I do, if there is a file that is being served by Node, then the user is going to be able to see the source code. 无论我做什么,如果Node正在提供一个文件,那么用户将能够看到源代码。 Is this just how Express works? 这就是Express的工作方式吗? Is it meant to be a development framework over a production framework? 它是否意味着要成为生产框架之上的开发框架?

Right now I am trying to send bad responses. 目前,我正尝试发送不良回复。

full server.js 完整的server.js

var path = require('path'),
   express = require('express'),

var app = express();

app.use('/', express.static(__dirname));
app.use('/', express.static('dist'));

// not working
app.get('/client/config/app.js', function(req, res) {
   res.sendStatus(400);
});

app.listen(3001, function() {
   console.log('listening');
});

I am able to send a response if I specify a directory path, but not if I specify a full file path. 如果指定目录路径,则可以发送响应,但是如果指定完整的文件路径,则不能发送响应。 This works: 这有效:

app.get('/client/config/', function(req, res) {
   res.sendStatus(400);
});

And this doesn't: 而且这不是:

app.get('/client/config/app.js', function(req, res) {
   res.sendStatus(400);
});

I've also tried routing with app.use . 我也尝试使用app.use路由。 That didn't work either. 那也不起作用。

The best thing I can do right now to "hide" the source code is to uglify it with Gulp, but I imagine it's easy to unravel it with a JS prettifier. 我现在要做的最好的事情就是“隐藏”源代码,就是用Gulp对其进行丑化,但是我想可以很容易地用JS Prettifier来解开它。

one line culprit 一线元凶

app.use('/', express.static(__dirname));

That line is saying its ok to pull anything. 那条线说可以拉任何东西。 You could replace it with: 您可以将其替换为:

app.use('/', express.static(__dirname + '/public'));

Then put stuff in the public directory you want viewed. 然后将内容放入要查看的公共目录中。 For routes you want to have as priority, place them before the other declarations. 对于要优先考虑的路由,请将其放在其他声明的前面。 So you would place: 因此,您将放置:

app.get('/client/config/app.js', function(req, res) {
 res.sendStatus(400);
});

above all else. 高于一切。 However, seems like you may not need it if you just fix the first problem, then you are good. 但是,如果您只解决第一个问题,似乎不需要使用它,那么您就很好。 Also, see HTTP status codes. 另外,请参阅HTTP状态代码。 You would probably want 404 or 403 for that type of file. 对于该类型的文件,您可能需要404或403。

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM