简体   繁体   中英

res.write doesn't work while the same thing works in console.log

the console.log in the showBets function is working fine, but not the res.write. Am i misunderstanding how it works? The documentation is not making me any wiser.

app.js

var queryString = 'SELECT * FROM bets';

router.get("/bets",function(req, res){
    showBets(res);
    res.sendFile(path + "bets.html");
});

function showBets(res){
    connection.query(queryString, function(err, rows, fields, res) {
        if (err) throw err;

        else{
            for (var i in rows) {
                res.write(rows[i].title);
                console.log(rows[i].creator);
            }
        }
    });
}

You should be careful about "res" variable

function showBets(res1){
    connection.query(queryString, function(err, rows, fields, res2) {
        if (err) throw err;

        else{
            for (var i in rows) {
                res1.write(rows[i].title);
                console.log(rows[i].creator);
            }
        }
    });

res1 and res2 are difference.

Fixed it by doing this:

function showBets(res) {
  var queryString = 'SELECT * FROM bets';

  connection.query(queryString, [], function(err, rows) {
    if (err) {
      console.log("aa: " + err);
      throw err;
    } 

    rows.forEach(function(row) {
      res.write(row.creator);
      console.log(row.creator);
    });

    res.end();
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM