我有一个有效的用户注册/登录页面,唯一剩下的就是根据用户是否登录来制作内容。读完后我想到了这个:
app.use(function(req, res, next) {
db.users.find({rememberToken: req.cookies.rememberToken}, function(err, foundUser) {
if (err) { next(); }
if (foundUser[0].length === 0) {
res.locals.isLoggedIn = false;
next();
} else {
res.locals.isLoggedIn = true;
next();
}
});
});
然后为了测试它,我在 Jade 模板中执行了此操作:
!!!
html
head
#{isLoggedIn()}
但发生的只是它说 isLoggedIn 未定义。
我找不到关于该主题的太多文档,因此任何信息都会很棒。谢谢!
我基本上想让该函数返回 true 或 false,以便我可以基于它加载内容。
最佳答案
首先,要获取函数的结果,您必须调用该函数,而不是像您那样渲染元素。要调用该函数,请使用以下语法:
p #{isLoggedIn()}
要渲染 HTML/jade 的一部分,您可以使用类似的东西
- if (isLoggedIn())
p User is logged in
您的代码示例的真正问题是您正在从 View 访问数据库,并且您正在 View 中使用不起作用的回调(下一个)。
更好且有效的方法是使用一些中间件在 res.locals 中设置 isLoggedIn
字段。
var isLoggedIn = function(req, res, next) {
db.users.find({rememberToken: req.cookie.rememberToken}, function(err, foundUser) {
if (err) { console.log('We have an error ' + err ); next();}
if (foundUser[0].length === 0) {
console.log('We could not find the user with the rememberToken ' + req.cookie.rememberToken);
res.locals.isLoggedIn = false;
next();
} else {
console.log('We found the user with the rememberToken ' + req.cookie.rememberToken);
res.locals.isLoggedIn = true;
next();
}
});
};
app.get('/yourroute', isLoggedIn, routes.yourroute);
关于javascript - 如何使用 Express 中的函数呈现 Jade 模板中的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15859530/