mysql - 在 node.js (express) 中获取 MySQL 数据并使用 EJS 打印

标签 mysql node.js express

我正在尝试获取我的 MySQL 表的数据并使用 EJS 在 HTML 中打印它们,但这不起作用。它告诉我 print not defined。我该怎么办?

router.get('/data', function(req, res){
    res.render('print', {req : req, res : res});
    connection.query('SELECT * FROM users', function(err, result) {

        if(err){
            throw err;
        } else {
            for(x in result){
                res.locals.print =  result[x];
                console.log(result[x]);
            }
        }
    });
});
<!doctype html>
<html>
    <body>
        <div>
            <%= print %>
        </div>
    </body>
</html>

最佳答案

在渲染中,您可以返回一个包含查询数据的 JSON 变量并显示在 View 中。 res.render 可以是最后一条指令。有些像这样:

var obj = {};
router.get('/data', function(req, res){

    connection.query('SELECT * FROM users', function(err, result) {

        if(err){
            throw err;
        } else {
            obj = {print: result};
            res.render('print', obj);                
        }
    });

});

<body>
    <table id="table" >  
        <thead>  
            <tr>  
                <th>Username</th>  
                <th>Password</th>  
            </tr>  
        </thead>  
         <tbody>  
         <% print.forEach(function (user) { %>
            <tr>  
                <td><%= user.username %></td>  
                <td><%= user.password %></td>
            </tr>                                   
         <% }) %>
         </tbody>
    </table>   
</body>

</html>

关于mysql - 在 node.js (express) 中获取 MySQL 数据并使用 EJS 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628453/

相关文章:

MySQL 获取每个条件的最后一条记录

node.js - 如何将 HTTP 响应传递给 Node.js 中的回调?

node.js - socket.io websocket 回退

javascript - 使用 handlebars.js 显示 JSON 数据

php - 最好运行 2 个 sql 查询或 1 个并处理重复的结果集?

c# - MySQL返回设置字段

Node.JS 不查询本地 DNS

node.js - 我可以在同一条路线上使用 2 个不同的功能吗? Node.js

javascript - 循环 Mongoose 数据数组

mysql 删除/var/lib/mysql my.cnf