NodeJS 会话认证 [英] NodeJS Session Authentication
问题描述
我正在尝试设置登录会话,以便所有应该限制登录的页面都直接重定向到登录屏幕.不幸的是,app.get
似乎表现得很奇怪,并且在某些情况下不会触发.
I'm trying to setup a logged in session so that all pages that should be login-restricted simply redirect to the login screen. Unfortunately, app.get
seems to be acting weird and not triggering for some cases.
比如我的认证函数:
function authenticate(req,res) {
var pass = false;
if (req.session.loggedIn) pass = true;
console.log(pass);
if (pass) {
next();
} else {
res.redirect("/html/login.html");
}
}
还有我的 server.js:
And my server.js:
app.use(express.static(__dirname));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session({secret: 'secretkey'})); //not my real key
//gets
app.get("/onePlayer",authenticate);
app.get("/",authenticate);
app.get("/logout",function(req,res) {
req.session.destroy();
res.redirect("/");
});
/
已通过身份验证,我可以在我的终端中看到它,但是 /onePlayer
根本不会触发,我无需登录即可进入该页面.
The /
gets authenticated, I can see it in my terminal, but /onePlayer
does not trigger at all, and I can get to the page without logging in.
注意:/onePlayer
是一个目录.主页是 onePlayer/index.html
(也试过完整路径,没有触发器).我还通过注销和销毁会话来确保会话被销毁.
Notes: /onePlayer
is a directory. The main page is onePlayer/index.html
(tried the full path as well, no trigger). I have also made sure that the session is destroyed by logging out and destroying the session.
为什么没有为 /onePlayer
调用该函数?我想不通.
Why is the function not being called for /onePlayer
? I can't figure it out.
推荐答案
这里的问题是 onePlayer
是一个目录,在你的代码中,你优先考虑存在的文件,而 然后到您的 app.get
调用.
The problem here is that onePlayer
is a directory and that in your code, you give priority first to files that exist, and then to your app.get
calls.
将您的代码更改为如下所示:
Change your code to look something like this:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session({secret: 'secretkey'})); //not my real key
app.get("/onePlayer",authenticate);
app.use(express.static(__dirname)); // Moved this after the app.get so that it has a lower priority
app.get("/",authenticate);
app.get("/logout",function(req,res) {
req.session.destroy();
res.redirect("/");
});
这篇关于NodeJS 会话认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!