问题描述
我使用Node(最新版本)+ Express,也是最新版本。我有2个文件夹,公共和安全。安全的文件夹只能在登录后才能访问。
I use Node (latest version) + Express, also latest Version. I have 2 folders, public and secured. The secured folder should only be accessible after login.
我自己创建了一个登录系统,现在我想知道如何保护路由到这个安全文件夹
I've create a login system by myself, now I wonder how I can secure the route to this "secure-folder".
我正在关于设置一个静态路由到我的安全文件夹(就像我做了一个公共的),然后检查用户是否登录,但是它不起作用。
I was thining about setting a static route to my "secured" folder (like I did with the public one) and then check whether the user is logged in, but it doesn't work.
这是我以为应该工作的...
This is what I thought should work...
(...)
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'secured')));
(...)
function requireLogin(req, res, next) {
if (req.session.loggedIn) {
next(); // allow the next route to run
} else {
// require the user to log in
res.redirect("/login");
}
}
app.all("/secured/*", requireLogin, function(req, res, next) {
next();
});
推荐答案
为您的私有静态单独指定一个不同的文件夹路线
Specify a different folder for your private statics on a separate route
app.use(express.static(path.join(__dirname, 'public')));
app.use('/private', express.static(path.join(__dirname, 'private')));
然后,您可以在每个请求中使用您的中间件
Then you can use your middleware on each request
app.all('/private/*', function(req, res, next) {
if (req.session.loggedIn) {
next(); // allow the next route to run
} else {
// require the user to log in
res.redirect("/login");
}
})
这篇关于如何使用Express和Nodejs来保护静态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!