简体   繁体   中英

Get MySQL data in node.js (express) and print using EJS

I'm trying to get the data of my MySQL table and print them in HTML using EJS, but this doesn't work. It tells me print not defined . What should I do?

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>

In the render, you can return a JSON variable with the consulted data and show in the view. res.render can be the last instruction in this way. Some like this:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM