【发布时间】:2023-03-13 02:34:01
【问题描述】:
我遇到了奇怪的问题。我相信这对有经验的人来说非常简单。
在Node.js+Express+NeDB上制作本地Web服务器
登录时客户端向/login 表单发出 POST 请求,并在成功登录时重定向。
{"id":1,"created":1568146217901,"username":"sprice","name":"Steve Price","email":"email@gmail.com","password":"Password","level":"1","_id":"3JDE7p6tAl1vD11k"}
登录帖
// POST services
app.post('/login', (req, res) => {
const loginData = req.body;
db.users.findOne({ username: loginData.uname }, function (err, doc) {
req.session.userId = doc.id;
if(doc.id === 1) console.log("True"); // < Output: True
console.log(req.session.userId); // < Output: 1
});
req.session.userId = 1; // < Just for test
res.redirect('/plan');
});
在进入/plan 页面之前,有一个身份验证检查:
const redirectLogin = (req, res, next) => {
const { userId } = req.session;
console.log(userId); // < Output: undefined
if (!userId) {
res.render('pages/index');
} else {
next()
}
}
所以我的奇怪问题是,如果我从 DB 中分配整数值并测试我是否有 if 语句,我会得到 req.session.userId = 1,但是当客户端被重定向时,它的 req.session.userId = undefined。
但是,如果我使用该测试线手动分配值,它可以工作并且服务器发出cookie,我可以毫无问题地访问我的网站......
我是不是做错了什么?
【问题讨论】:
标签: node.js authentication express-session nedb