使用传递的对象渲染ejs模板

时间:2014-08-04 20:15:29

标签: node.js express

由于某种原因,以下对象未正确传递到页面。

我能够使用此函数调用console.log,该函数返回已登录用户的json对象。

app.use(function(req, res, next){
console.log(req.user);
  next();
});

但是,当我通过路线将其存储为变量时,它会显示为undefined。知道脱节的地方吗?

app.get('/', function(req, res) {
    res.render('index.ejs',{
      bootstrappedUser: req.user
    });
});

bootstrappedUser in" bootstrappedUser中的以下结果未定义"

<body ng-app="hcApp">
<script>
  console.log(bootstrappedUser);
</script>

1 个答案:

答案 0 :(得分:0)

您的最新代码段由您的服务器呈现,但由客户端的浏览器执行。因此,您的浏览器不知道bootstrappedUser是什么。

但是,如果你这样做:

<body ng-app="hcApp">
<script>
  console.log("#{bootstrappedUser}");
</script>
...

服务器将代码呈现给(假设bootstrapUser等于foo):

<body ng-app="hcApp">
<script>
  console.log("foo");
</script>
...

现在,客户端的浏览器可以毫无问题地执行代码。

编辑:抱歉,您使用的是EJS模板(不是玉石)。因此,要呈现变量:<%= bootstrappedUser %>

<body ng-app="hcApp">
<script>
  console.log("<%= bootstrappedUser %>");
</script>
...
相关问题