首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将MySQL JSON对象从connection.query()传递给res.render()

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

Stack Overflow用户
提问于 2015-10-16 12:46:24
回答 1查看 275关注 0票数 1

正如标题所示,我在从MySQL响应访问connection.query()函数之外的对象时遇到了困难。

代码语言:javascript
复制
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
  });
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-16 12:48:28

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

代码语言:javascript
复制
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.');
        }
    });
});

注意:在回调函数之外使用testimonials时会得到testimonials,因为方法connection.query是异步的,它将在您的res.render方法之后运行

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33170866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档