Passing values between Express and EJS

0

I have a foo value that is obtained in an asynchronous method in a db.js file.

The query is being performed normally and I can already capture the data of the foo variable in my index.js file, but when trying to perform a forEach passing foo to my index.ejs file, it informs that foo is not defined

index.js

const express = require('express');
const app = express();
const db = require('./db/db.js');

db.getData().then(function (result) {
    runServer(result);
}).catch(function (error) {
    console.log(error);
});

function runServer(foo) {
    app.set('view engine', 'ejs');

    // index page
    app.get('/', function(req, res) {
        res.render('pages/index', foo);
    });

    app.listen(8080);
}

index.ejs

...
<ul>
  <% foo.forEach(function(element) { %>
  <li><%= element.id %> - <%= element.nome %></li>
  <% }); %>
</ul>
...

db.js (I can not believe the problem is here)

const sql = require("mssql")
const s = "SELECT ..."

const c = {
    user: "...",
    password: "...",
    server: "...",
    database: "..."
}

function execQuery(config, sqlQuery) {
    return new Promise(function (resolve, reject) {
        const conn = new sql.ConnectionPool(config)
        const req = new sql.Request(conn)

        conn.connect(function (err) {
            if (err) {
                console.log(err)
                return
            }
            req.query(sqlQuery, function (err, recordset) {
                if (err) {
                    console.log(err)
                } else {
                    resolve(recordset.recordset)
                }
                conn.close()
            })
        })
    })
}

module.exports.getData = async function() {
    let data = await execQuery(c, s)
    return data
}
    
asked by anonymous 04.09.2017 / 23:01

1 answer

2

You have to pass an object to render with the keys you want to be variables inside the ejs.

In other words, instead of res.render('pages/index', foo); you should use this way:

 res.render('pages/index',{foo: foo});

If you have more data, add other properties:

 res.render('pages/index',{foo: foo, bar: 1234, titulo: 'minha página'});
    
04.09.2017 / 23:10