0

I use node express app with the mssql package (https://www.npmjs.com/package/mssql) to read data from my Azure SQL Server database. In general, I could read the table in the database, however, I don't know how to visualize the table into front page which I use handlebars template for node.

Here is my code:

routes/index.js

const express = require('express');
const router = express.Router();
const config = require('../dbconfig');
const sql = require('mssql');

// Get homepage
router.get('/', function(req, res) {    

  // Read data rows from the database (dbo.lendbook table)
  new sql.ConnectionPool(config).connect().then(pool => {
    return pool.query `select * from dbo.lendbook`
  }).then(result => {
    res.render('index');
      // Output the data which was read in the terminal:
    //  console.dir(result);
  }).catch(err => {
    console.log(err);
  });

views/index.handlebars

<h2 class="page-header">Dashboard</h2>
<p>Welcome to your dashboard</p>

{{#each rows}}
   <div>{{item}}</div>
{{/each}}

This is the table from the database I could read by the function above

enter image description here

Aaron Chen
  • 9,835
  • 1
  • 16
  • 28
Hoàng Nguyễn
  • 1,121
  • 3
  • 33
  • 57

1 Answers1

0

Try this:

routes/index.js

new sql.ConnectionPool(config).connect().then(pool => {
    return pool.query `select * from dbo.lendbook`
}).then(result => {

    res.render('index', {
        rows: result.recordset
    });

}).catch(err => {
    console.log(err);
});

views/index.handlebars

<h2 class="page-header">Dashboard</h2>
<p>Welcome to your dashboard</p>

<table>
    {{#each rows}}
        <tr>
            <td>{{this.id}}</td>
            <td>{{this.rate}}</td>
            <td>{{this.amount}}</td>
        </tr>
    {{/each}}
</table>
Aaron Chen
  • 9,835
  • 1
  • 16
  • 28