簡體   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

所以在我的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM