首页 > 解决方案 > Express MySQL api 需要帮助返回查询

问题描述

我有通过 get 请求返回 JSON 数据的 express api。它正在从 MySQL 数据库中获取数据。

当我返回示例数据 JSON 时,它工作正常。但是,我对如何从 MySQL 返回查询数据感到困惑。

我知道我正在获取数据,因为我做了 console.log(rows[0]) 并且它打印了我想要的数据,但我不知道如何发送它。

感谢您的帮助

/* GET users listing. */
router.get('/2018-2017/2', function(req, res, next) {


connection.query('CALL BRWally.spGetDealerships()', function (err, 
rows, fields) {
 if (err) throw err

  console.log('The solution is: ', rows[0])
})

/* rows[0] contains the data i want to return.

I am unsure how to send it.

To send static JSON data i have done...

res.json(
  [{
  id: 1,
  week: "15",
  year: "2016-2017",

  }

]);

*/
res.send({data: rows[0]});
});


/* terminal output */
You are now connected...
GET /users/2018-2017/2 404 15.324 ms - 156
The solution is:  [ RowDataPacket { PK_DealershipName: 'Guelph             
Auto Mall' },
  RowDataPacket { PK_DealershipName: 'Sports World' },
  RowDataPacket { PK_DealershipName: 'Waterloo' } ]

标签: node.jsexpress

解决方案


您只需将“发送”移动到查询函数回调内部。

router.get('/2018-2017/2', function(req, res, next) {
  connection.query('CALL BRWally.spGetDealerships()', function (err,   rows, fields) {
    if (err) throw err
    res.send({data: rows[0]});
    console.log('The solution is: ', rows[0])
  })
});

推荐阅读