简体   繁体   English

Express MySQL api需要帮助返回查询

[英]Express MySQL api need help returning query

I have express api that is returning JSON data via get request.我有通过 get 请求返回 JSON 数据的 express api。 It is getting the data from MySQL database.它正在从 MySQL 数据库中获取数据。

It is working fine when i return a sample data JSON.当我返回示例数据 JSON 时它工作正常。 However, I am confused with how to return the query data from MySQL.但是,我对如何从 MySQL 返回查询数据感到困惑。

I know i am getting the data since i do console.log(rows[0]) and it prints the data i want but i cannot figure out how to send it.我知道我正在获取数据,因为我执行了 console.log(rows[0]) 并且它打印了我想要的数据,但我不知道如何发送它。

Thank for the help感谢您的帮助

/* 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' } ]

you just have to move the "send" to inside the query function callback.您只需将“发送”移动到查询函数回调中。

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])
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM