[英]Why is my simple if check, if user is there, throwing an error in my ejs view. If var not there, I specify something else, but still doesn't work
所以在我的 header.ejs 中我有一些非常简单的东西:
<% if (user) { %>
hello
<% } %>
现在,每当我运行时,我都会收到一个 500 错误,这很奇怪,因为我认为如果user
不存在,那么它会跳过{}
,但似乎没有。
查看路由器
现在在我看来路由器我做router.use(authController.isLoggedIn);
执行此代码:
exports.isLoggedIn = async (req, res, next) => {
if (req.cookies.jwt) {
try {
// 1) verify token
const decoded = await promisify(jwt.verify)(
req.cookies.jwt,
process.env.JWT_SECRET
);
// 2) Check if user still exists
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next();
}
// 3) Check if user changed password after the token was issued
if (currentUser.changedPasswordAfter(decoded.iat)) {
return next();
}
// THERE IS A LOGGED IN USER
res.locals.user = currentUser;
return next();
} catch (err) {
return next();
}
}
next();
};
所以,这将在访问任何视图之前被调用(我猜*),因为我使用它比任何其他路线都更高,就像代码中的更高线一样。
现在,如果我将一个变量传递给 header.ejs 文件,如下所示:
exports.getLogin = async (req, res, next) => {
res.status(200).render('login', {
age: 16
});
};
那行得通,但我不明白我做错了什么,因为我的参考资料和源材料似乎正是这样做的(如上所述),但我没有做任何事情似乎可以解决它。 很抱歉问了这么简单的问题,我真的一直在研究四处寻找答案。 我搜索了 stackOverflow,并阅读了 ejs 文档,但我似乎看不到问题所在。
您是否尝试过使用 else 语句来检查是否可以避免错误?
<% if (user) { %>
hello
<% } else {%>
user doesn't exists
<% } %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.