Saturday 26 August 2017

Node.js beginner, question about MySQL + HTTP

So I'm following this tutorial at http://ift.tt/1BZEETG. I understood how to connect to DB and get results. Now I want to show the result through a browser. This is what I got:var mysql = require('mysql'); var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); var con = mysql.createConnection({ host: "localhost", user: "xxxxxx", password: "xxxxxx", database: "xxxxxx" }); con.connect(function(err) { if (err) { console.log("Error on connect"); throw err; } console.log("Connected!"); var sql = "SELECT * FROM test"; con.query(sql, function (err, result, fields) { if (err) { console.log("Error on query"); throw err; } for(var i = 0; i < result.length; ++i) { var row = result[i]; var id = row.id; var name = row.name; var address = row.address; res.write("id: " + id + ", name: " + name + ", address: " + address + "
"); } res.end("End"); }); }); }).listen(8080); My question is about con.query(). I've observed that this is an async call because if I place res.end() after that block, it causes a "write after end" error. If this is the case, how do you perform multiple queries then?

Submitted August 26, 2017 at 08:52AM by davenirline

No comments:

Post a Comment