首页 > 解决方案 > 将数据从服务器发送到客户端nodejs

问题描述

我有这段代码,可以让我获取用户在我的数据库中发布的所有帖子。问题是我试图将该数据发送到前端(客户端)。但我没有成功,我不知道我错过了什么,

从 mongoDB 中提取用户信息的代码如下。代码运行良好,没有问题,

User.find({}).lean(true).exec((err, users) => {
      let userMap = [];

            userMap.push({ user: users[i], posts: users[i].posts[j] });
       //all the data are stored to userMAP :[{user : xxxxx ,posts : {the posts are here}}]
          }
        }

      }
      console.log(userMap);

      User.findOne({ userName: req.user.userName }, (error, req_user) => {

        console.log(req.user.lastLogin)
        let lastSeen = ta.ago(req.user.lastLogin);

        //console.log(posts)
        res.render('home', { // this part for rendering the homePage and send data
          user: req_user,
          people: users,
          userMap: userMap.reverse()
        });
      });

我在客户端代码中尝试的是:

  <div class="container">

        <% for(var x=0;x<user.posts.length;x++) { %>
    <div class="jumbotron">
        <div>by
            <b>{{ user.posts[x].author }}</b>
            on
            <small>{{ user.posts[x].createdAt }}</small>
        </div>

        <div>
            <p>{{ user.posts[x].caption }}</p>
        </div>

        <div class="row">
            <button onclick="actOnPost(event);"
                    data-post-id="{{ this.id }}">Like
            </button>
            <span id="likes-count-{{ this.id }}">{{ this.likes_count }}</span>
        </div>
    </div>
    <% } %>

对于错误部分,我什么也没得到,

这是我在数据库中存储的数据的图像

在此处输入图像描述

这是主页的图像

在此处输入图像描述

我的代码的场景:

1-我正在使用 EJS 视图引擎,当用户登录home.ejs显示在服务器端时,我使用上面的代码准备我需要显示的数据

2-除了在客户端显示数据外,一切都运行良好home.ejs

3-从我的服务器调用该页面我将此语句与上述代码混合使用

router.get('/home', (req, res) => {
  if (req.user.id) {
    console.log(req.user.id)
    User.find({}).lean(true).exec((err, users) => {
      let userMap = [];

在客户端显示数据的任何帮助或更好的解决方案,

此致,

标签: javascriptnode.jsmongodbejs

解决方案


这不是在 ejs 中显示数据的语法,试试这个。查看这些文档

<%= 将值输出到模板中(HTML 转义)

    <% for(var x=0;x<user.posts.length;x++) { %>
<div class="jumbotron">
    <div>by
        <b><%= user.posts[x].author %></b>
        on
        <small><%= user.posts[x].createdAt %></small>
    </div>

    <div>
        <p><%= user.posts[x].caption %></p>
    </div>

    <div class="row">
        <button onclick="actOnPost(event);"
                data-post-id="<%= this.id %>">Like
        </button>
        <span id="likes-count-<%= this.id %>"><%= this.likes_count %></span>
    </div>
</div>
<% } %>

推荐阅读