Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output result of a mysql query as a json file in node.js

What i have her is this

app.post('/login', function (req, res){
  connection.connect();
  email = req.body.email;
  password = req.body.password;
  if(email && password ) {
    console.log(email);
    console.log(password);
   // connection.query('SELECT username FROM user WHERE email =? and password = ?', [email, password], 
   // function (error, rows, fields) { 
    connection.query('SELECT * FROM user ', 
    function (error, rows, fields) {
      var str='';
      for (var i = 0;i < rows.length; i++) {
        str = str + rows[i].username;
        res.end(str);
      }
      connection.end(); 
    }); 
  }
});

so instead of just displaying the result i want it to be something like this:

{
 "username": "ABC",
 "username": "DEF",
 "username": "HIJ"
}
like image 536
Rawan Hamdi Avatar asked Mar 18 '23 04:03

Rawan Hamdi


1 Answers

The first problem is you're not actually building the object you want. The second problem is you're not building an array of them. Finally, you need to convert that array into JSON if the res object doesn't have something like res.json.

var objs = [];
for (var i = 0;i < rows.length; i++) {
    objs.push({username: rows[i].username});
}
connection.end();
res.end(JSON.stringify(objs));
like image 136
Mike Perrenoud Avatar answered Mar 20 '23 18:03

Mike Perrenoud