I'm developing a project on Node.JS with Express, MySQL and Socket.IO. When the user opens the main page provided by the server, the request must cause data to be read from the database and sent to the client for it to be listed on the page.
The problem is that before the data can be sent, the server sends the page to the client and this causes the data not to be read from the BD or sent to the socket. I tried using async to make all the functions run in order, but it did not work.
My code:
app.all("/", function(req, res){ //Função para qualquer requisição HTTP (GET ou POST)
var query1 = 'SELECT ? FROM tabela1;', query2 = 'SELECT ? FROM tabela2;';
function qSelect(callback, queryTxt){ //Realiza queries de seleção no bd
db.query(queryTxt, ['*'], function(err, results){
if(err){
console.log("Error on:");
callback();
return null;
}
callback();
return results;
});
}
async.series( //Executa comandos em série
[qSelect(console.log("Table 1 data query."),query1),
qSelect(console.log("Table 2 data query."),query2),
sendDataClient(console.log("Data sent to client."))],
function (err, output){ //Função executada após funções enfileiradas em série
if(err){
console.log("Error!! Sending database data to client did not result in success.");
data = [null, null];
} else{
data = output;
}
io.on("connection", function(callback, socket){
socket.emit("appData", {msg: "Schedule and Contact Data", content: data});
socket.on("Return", function (data){
console.log(data.content);
});
});
}
);
res.sendFile("index.html"); //Envia página html ao cliente
});
In case I use Express exclusively to handle http pages and requests. Socket.IO is for sending binary or text data to be used in javascript on the client side.