-1

I have express api that is returning JSON data via get request. It is getting the data from MySQL database.

It is working fine when i return a sample data JSON. However, I am confused with how to return the query data from 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.

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' } ]
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Jan 08 '19 at 01:09

1 Answers1

0

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])
  })
});
aquilesb
  • 2,182
  • 1
  • 19
  • 19