Home Unable to send object in Express response
Reply: 1

Unable to send object in Express response

JorahFriendzone
1#
JorahFriendzone Published in 2017-12-07 18:48:02Z

I'm trying to send all the data from my database back using res.send, but it's throwing me an error. On my frontend, I'm calling the endpoint select and trying to return all rows and data within the database.

app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      res.send(row);
    }
  })
});
Luca
2#
Luca Reply to 2017-12-07 18:53:03Z

You should use res.write instead of res.send as the latter terminates the function (nothing after the first use of res.send is executed)

app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      res.write(row);
    }
    res.end(); //this finally sends the response
  })
});

Or if you want to use res.send send the whole rows array:

app.get('/select', function (req, res) {
    con.query('SELECT * FROM Contracts', function (err, rows, fields) {

    if (err) {
      console.log(`Error: ${err}`);
    }

    res.send(rows);
  })
});
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344271 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO