[英]NodeJS Session Authentication
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. 不幸的是,
app.get
似乎表现app.get
奇怪,并且在某些情况下不会触发。
For example, my authentication function: 例如,我的身份验证功能:
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");
}
}
And my server.js: 而我的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("/");
});
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
根本没有触发,我可以在不登录的情况下访问该页面。
Notes: /onePlayer
is a directory. 注意:
/onePlayer
是一个目录。 The main page is onePlayer/index.html
(tried the full path as well, no trigger). 主页面是
onePlayer/index.html
(也尝试了完整路径,没有触发器)。 I have also made sure that the session is destroyed by logging out and destroying the session. 我还确保通过注销和销毁会话来销毁会话。
Why is the function not being called for /onePlayer
? 为什么没有为
/onePlayer
调用该函数? I can't figure it out. 我无法弄清楚。
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. 这里的问题是
onePlayer
是一个目录,在你的代码中,你首先优先考虑存在的文件, 然后优先考虑你的app.get
调用。
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("/");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.