javascript - 如何使用 Express 中的函数呈现 Jade 模板中的内容?

标签 javascript node.js express

我有一个有效的用户注册/登录页面,唯一剩下的就是根据用户是否登录来制作内容。读完后我想到了这个:

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/

相关文章:

javascript - Passport 身份验证引用错误: user is not defined

javascript - 为什么 $(document).ready();不明确的?

javascript - 添加类仅在数组中的最后一个 div 上执行

javascript - 减少 Highcharts 中列之间的空间

javascript - MongoDB .find 在 shell 中有效,但在 js 中无效

node.js - 独立 WatchOS6 应用程序的 APNS 失败

javascript - PhantomJS 在按钮单击事件后捕获下一页内容

node.js - 当覆盖下划线字段时,Sequelize 不会清理 dataValues

node.js (express) 链接 css/js

node.js - 在 hbs 中表达 res.locals.someVariable 的使用(handlebars 模板)