如何将一个MySQL JSON对象从connection.query()传递给res.render()

时间:2015-10-16 12:46:25

标签: javascript node.js

正如标题所示,我无法从connection.query()函数之外的MySQL响应中访问对象。

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

    var testimonials;

    // Running database queries
    connection.query('SELECT * FROM testimonials', function(err, rows, fields) {
        if (!err) {
            testimonials = rows;
            console.log(testimonials); // THIS WORKS
        }
        if (err) {
            console.log('Error performing database query.');
        }
    });


  res.render('index', {
      title: 'Title',
      description: 'Description in here.',
      testimonials: testimonials // THIS RETURNS UNDEFINED
  });
});

1 个答案:

答案 0 :(得分:0)

您应该将res.render放在回调函数中,例如:

router.get('/', function(req, res) {    
    var testimonials;

    // Running database queries
    connection.query('SELECT * FROM testimonials', function(err, rows, fields) {
        if (!err) {
            testimonials = rows;

            res.render('index', {
                title: 'Title',
                description: 'Description in here.',
                testimonials: testimonials // this will work!!!
            });
        }
        if (err) {
            console.log('Error performing database query.');
        }
    });
});

注意:在回调函数之外使用undefined时会得到testimonials,因为方法connection.query是异步的,并且> <{strong>之后<{>} res.render方法。