user3187759 user3187759 - 2 months ago 8
Node.js Question

send data to express.js in a for loop

I need help with this, I really can't crack this one up.
I have this web site using

Node.js
to call
mySQL
queries and display them as tables, each in it's own page. To do so, I created 4 objects that include a name, a title and the query. when I have this code going four times (from
queryPage[0]
to
queryPage[3]
), It works great. But i want to put it into a for loop so I won't need 4 repetitions of the same lines, but then it doesn't work. the pages don't load... Any idea what is going on?

connection.query(queryPage[0].query, function(err, rows) {
var arr = [];
for (var i in rows) {
arr[i] = rows[i];
}
app.get('/' + queryPage[0].name, function(req, res) {
res.render('pages/' + queryPage[0].name, {
title: queryPage[0].title,
data: arr
});
});
});

Answer

I think you need something more like this

var queryPage = [ ... ];
// This route catches all request
app.get('/:name', function (req, res, next) { 
    // :name = req.params.name

    var page;
    for(var i = 0, l = queryPage.length; i < l; i++)
        if(queryPage[i].name === req.params.name) {
            page = queryPage[i];
            break;
        }

    // Check the page exists
    if(!page) return res.status(404).send('Not found');
    // if(!page) return next();

    connection.query(page.query, function(err, rows) {
        res.render('pages/' + page.name , {
            title: page.title, 
            data: rows
        });
    });
});