我有通过get请求返回JSON数据的快速api。它正在从MySQL数据库获取数据。
当我返回示例数据 JSON 时,它工作正常。但是,我对如何从MySQL返回查询数据感到困惑。
我知道我正在获取数据,因为我做了控制台.log(行[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' } ]
您只需
将"send"移动到查询函数回调内部即可。
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])
})
});