顾名思义,我无法从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
  });
});

最佳答案

您应该将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是异步的,它将在res.render方法之后运行。

07-24 17:51