[英]How to turn off app.use(express.static('/public')); Express js
I am using Express js. 我正在使用Express js。 In the root folder, I have a
public
folder which contains subfolders stylesheets
, javascripts
, fonts
, images
and html
. 在根文件夹中,我有一个
public
其中包含子文件夹stylesheets
, javascripts
, fonts
, images
和html
。 I want to protect my assets if the user is not logged in. For example, if someone opens the web browser and without login make a request for http://localhost:3000/images/hello.jpg
then the request should be redirected to login page. 如果用户未登录,我想保护我的资产。例如,如果某人打开Web浏览器但未登录,则请求
http://localhost:3000/images/hello.jpg
则该请求应重定向到登录页面。
To achieve this I am using express.static(path.join(__dirname, '/public'))
conditionally. 为此,我
express.static(path.join(__dirname, '/public'))
使用express.static(path.join(__dirname, '/public'))
。
Challenge 1 挑战1
Login page also having some 4 to 5 assets (CSS and JS files), which are placed in the same public folder. 登录页面还具有大约4到5个资产(CSS和JS文件),它们位于同一公用文件夹中。
Challenge 2 挑战2
I am using this code express.static(path.join(__dirname, '/public'))
like this: 我正在像这样使用这段代码
express.static(path.join(__dirname, '/public'))
:
if(userIsLoggedIn){
express.static(path.join(__dirname, '/public'))
}else{
//what to do here???
//I need a code here which makes public folder as non-static folder
}
For example, we have 2 users A and B. Both users are using different computers. 例如,我们有两个用户A和B。两个用户都使用不同的计算机。 User A is doing successful login and at the server, we are setting the
public
folder as static
but user B has not done login he is now directly accessing the assets and he is able to access. 用户A是做成功登录,并在服务器上,我们设置的
public
文件夹static
但用户B没有做过登录他现在直接访问的资产,他是能够访问。
This is happening because we are not setting the public folder as static on user basis we are making it static if any of user do a successful login. 之所以发生这种情况,是因为我们没有将基于用户的公用文件夹设置为静态,如果有任何用户成功登录,则将其设为静态。
you can add an extra middleware before the express.static
to force a user validation. 您可以在
express.static
之前添加一个额外的中间件,以强制用户验证。
var VerifyUser = require('./verifyuser');
app.use(VerifyUser, express.static(__dirname + '/public'));
//VerifyUser code
module.exports = function(req, res, next) {
if(user.isLogged)
next();
else
next(err); //presume you have some error handler middleware
};
A quick way would be to simply mkdir an empty directory and point to it. 一种快速的方法是简单地mkdir一个空目录并指向它。 Or add files to it that you don't mind having public.
或向其中添加您不希望公开的文件。
express.static(path.join(__dirname, '/someemptydirectory'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.