簡體   English   中英

Express MySQL api需要幫助返回查詢

[英]Express MySQL api need help returning query

我有通過 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])
  })
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM