2
I am developing a Node.JS project 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 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 in the socket. I tried using async to make all the functions run in order, but it didn’t 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 the case use Express exclusively to handle http pages and requests. Socket.IO is for sending binary data or text to be used in javascript on the client side.
Where are you calling the callback of this line
io.on("connection"
? I think you need to have theres.sendFile
inside the callback of theasync.series
, how it’s going before theascync
series begin...– Sergio