这是我的 profile.hbs 文件,我的数据库使用 Express Node 和 MySQL。如果我想显示我登录用户的用户名。我应该在哪里进行查询以及如何进行查询。是在app.js或index.js里面(它有我所有的路由),还是在profile.hbs里面。我的项目的所有文件都在 this link 中
{{> header }}
<div>
<h2>Profile</h2>
</div>
Hi
</div> <!--Container-->
{{> footer-end}}
最佳答案
您的 profile.hbs 只是一个模板,用于根据接收到的数据创建 html 内容。
您可以从要渲染 profile.hbs 的路由中查询 Mysql,如下所示
router.get('/getuser/:userid', function(req, res) {
var userid = req.params.userid;
db.query('SELECT * from users where id = ?', userid, function(error, results, feilds) {
if (error) {
console.log("error ocurred while getting user details of " + userid, error);
res.send({
"code": 400,
"failed": "error ocurred"
});
} else {
res.render("edituser",{user:results});
}
});
});
这将使用用户的 json 呈现 edituser.hbs 文件。
您可以在 hbs 文件中使用它,例如:
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
这会渲染出这样的东西
<td>Test User</td>
<td>testuser1</td>
<td>test@example.com</td>
关于javascript - 如何在 .hbs 文件中执行 sql 查询,就像我们使用 php 执行 for .html 一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011060/