简体   繁体   English

为什么我的简单 if 检查,如果用户在那里,在我的 ejs 视图中抛出一个错误。 如果 var 不存在,我指定其他内容,但仍然不起作用

[英]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

so in my header.ejs I have something very simple:所以在我的 header.ejs 中我有一些非常简单的东西:

<% if (user) { %> 
hello
<% } %>

Now anytime I run that I get an error a 500 error, which is strange because I thought that if user didn't exist then it would skip over the {} , but it doesn't seem to.现在,每当我运行时,我都会收到一个 500 错误,这很奇怪,因为我认为如果user不存在,那么它会跳过{} ,但似乎没有。

Views Router查看路由器

Now in my views router I do router.use(authController.isLoggedIn);现在在我看来路由器我做router.use(authController.isLoggedIn); which does this code:执行此代码:

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();
};

So, this would be called (I guess*) before accessing any view because I use it higher up, like a higher line up in the code, than any of the other routes.所以,这将在访问任何视图之前被调用(我猜*),因为我使用它比任何其他路线都更高,就像代码中的更高线一样。

Now if I pass in a variable to the header.ejs file like this:现在,如果我将一个变量传递给 header.ejs 文件,如下所示:

exports.getLogin = async (req, res, next) => {
  res.status(200).render('login', {
    age: 16
  });
};

That works, but I don't understand what I'm doing wrong because my references and source materials seem to be doing it exactly this way (as I described above) yet with mine nothing I do seems to fix it.那行得通,但我不明白我做错了什么,因为我的参考资料和源材料似乎正是这样做的(如上所述),但我没有做任何事情似乎可以解决它。 I'm sorry for asking such a simple question, I really have been researching all around and looking for the answer.很抱歉问了这么简单的问题,我真的一直在研究四处寻找答案。 I searched stackOverflow, and read the ejs documentation but I can't seem to see the issue.我搜索了 stackOverflow,并阅读了 ejs 文档,但我似乎看不到问题所在。

Have you tried using an else statement just to check if that avoids the error?您是否尝试过使用 else 语句来检查是否可以避免错误?

<% if (user) { %> 
hello
<% } else {%>
user doesn't exists
<% } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM