node.js - 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' } ]
解决方案
您只需将“发送”移动到查询函数回调内部。
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])
})
});
推荐阅读
- ng-bootstrap - 如何使用 Ng-Bootstrap 6 在 Angular 9 中正确实现 Tooltip
- python - 如何提取Json数据并导出为csv
- groovy - 如何在src下导入groovy文件
- npm - 如何使用 AWS Codecommit 存储库作为 npm 依赖项
- android - react-native-video 示例抛出“TypeError:undefined”错误
- java - 如何将资源池与机架系统连接?
- azure - 从 Windows 桌面应用程序调用具有 AD 授权的 Azure 函数
- if-statement - Ansible 中参数的 if 条件
- flutter - 如何验证 Stepper 中的每个表单步骤
- python - 在 Python 中使用凭据连接到 SQL Server