Passage of values between Express and EJS

Asked

Viewed 611 times

0

I possess a value foo which is obtained in an asynchronous method in a file db.js.

The query is being performed normally and I can already capture the variable data foo in my file index.js, but while trying to hold a foreach by passing foo to my file index.ejs, he 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 don’t think 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
}

1 answer

2


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

That is, in time of res.render('pages/index', foo); you should wear it like this:

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

and if you have more data, add other properties:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.