Mysql
 SQL >> Database >  >> RDS >> Mysql

Recuperare dati MySQL in Node.js (Express) e renderli con EJS

Puoi restituire i dati della query come variabile tramite res.render, che dovrebbe essere l'ultima istruzione della tua rotta, e poi ciclarci sopra nella vista. Qualcosa del genere:

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> 

Il controller esegue la query e passa le righe a EJS, mentre il template itera su di esse per costruire la tabella dinamicamente.