gpt4 book ai didi

javascript - 将数据从服务器发送到客户端nodejs

转载 作者:行者123 更新时间:2023-12-01 16:17:55 25 4
gpt4 key购买 nike

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

从 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>
<% } %>

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

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

enter image description here

这是主页的图像

enter image description here

我的代码的场景:

1- 我正在使用 EJS View 引擎,当用户登录 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 = [];

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

最好的祝福,

最佳答案

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

<%= Outputs the value into the template (HTML escaped)


    <% 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>
<% } %>

关于javascript - 将数据从服务器发送到客户端nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61560430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com