javascript - 将数据从服务器发送到客户端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 = [];
在客户端显示数据的任何帮助或更好的解决方案,
此致,
解决方案
这不是在 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>
<% } %>
推荐阅读
- vue.js - 使用Vue js如何在不刷新页面的情况下显示更新后的数据?
- javascript - 使用 Matter.js 的 HTML 元素
- javascript - 向画布添加事件侦听器?
- r - 从 BASE R 函数中捕获特定错误消息
- excel - ".Find Date" 在月中点中断
- discord.py - Discord.py 重写让机器人响应 DM
- reactjs - 从 useHooks() 返回的对象作为道具传递,不会在成员列表中的 handleDelete 之后重新渲染子组件
- vim - 使用 Clojure CLI 时无法使用 fire.vim 评估 ClojureScript
- python-3.x - 对 API 的 POST 请求失败
- python - 使用返回不正确值的python函数向熊猫数据框添加转义字符