javascript - 如何在 .hbs 文件中执行 sql 查询,就像我们使用 php 执行 for .html 一样?

标签 javascript node.js express

这是我的 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/

相关文章:

javascript - 谷歌驱动器范围 'Error Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.'

javascript - html5 需要验证在浏览器上运行良好,但在 phonegap 应用程序上运行良好

javascript - 无法理解 MDN 文档中 Promise.prototype.then() 的注释

node.js - 如何在 typescript 中使用 "debug"模块

node.js - npm WARN 已弃用 node-uuid@1.4.8 : Use uuid module instead

javascript - Angular ngResource 不适用于 Controller

javascript - 类型 `user` 上不存在属性 `Session & Partial<SessionData>`

javascript - Node : TypeError: Buffer is not a function (but it's a function! )

javascript - ES6 类中转换的函数对象字面量

javascript - 为什么 JavaScript 接受具有重复属性的对象?