Reputation: 13091
I made a route using NodeJS and Express and can connect to Database and retrieve data.
How to push the whole response into 1 JSON object (instead of printing as a console print):
app.get('/db', function(req, res){
connection.execute({
sqlText: sqlStatement,
complete: function(err, stmt, rows) {
if (err) {
console.error('Failed to execute statement due to the following error: ' + err.message);
} else {
console.log('Number of rows: ' + rows.length);
console.log('Rows:');
for (row in rows)
console.log(JSON.stringify(rows, null, 2));
}
},
});
res.send({ name: 'done' });
});
Upvotes: 0
Views: 645
Reputation: 4383
Assuming that everything else is working correctly (where is sqlStatement
defined?), what you want to do is to use res.json(), like:
app.get('/db', function(req, res) {
connection.execute({
sqlText: sqlStatement,
complete: function(err, stmt, rows) {
if (err) {
var error = 'Failed to execute statement due to the following error: ' + err.message;
console.error(error);
return res.send(error);
} else {
console.log('Number of rows: ' + rows.length);
console.log('Rows:');
return res.json({data: rows, message: 'done'});
}
},
});
});
Upvotes: 1