NODE.js with socket and Mysql

Asked

Viewed 395 times

0

I have a problem with Node, I believe it must be something related to callback s, but I’m not sure, but anyway, my problem is basically in pulling data from a database Mysql, this data will be stored in a variable called msg. My complete code is this:

        const express = require('express');
        const path = require('path');
        const app = express();
        const server = require('http').createServer( app );
        const io = require('socket.io')(server);
        const mysql = require('mysql');

        // conexao com o banco de dados 
        var con = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database: "dados_users"
        });


        app.use(express.static(path.join(__dirname,'public')));
        app.set('views',path.join(__dirname,'public'));


        app.engine('html',require('ejs').renderFile);
        app.set('view engine','html');

        app.use('/', ( request , res ) => {
            res.render('index.html');
        });

        let msg =[];  

        io.on('connection', socket => {

        //este select deve retornar as mensagens que estão no banco para a 
        //variavel msg
        // con.connect(function(err) {
        //     con.query('SELECT * FROM dados', function(err, rows, fields) {
        //         if (err) throw err;
        //           msg = rows;
        //     });
        // });

        socket.emit('msg_existentes',msg);    //retorna dados earmazenados na variavel msg 
        socket.on('recebe_do_front', data => {



        console.log(msg);

        // con.connect(function(err) {
        //     var sql = "INSERT INTO dados (nome, msg) VALUES ('"+data.nome+"', '"+data.msg+"')";
        //     con.query(sql, function (err, result) {
        //     if (err) throw err;
        //         console.log("1 record inserted");
        //     });
        // });

        msg.push( data );     //manter msg na section da pagina
        socket.broadcast.emit('envia_para_usuario', data);   //retorna msg do canudo 
    });
});
server.listen(3001);

The function that is not doing the part of it is the function of [ select ], this below:

   //este select deve retornar as mensagens que estão no banco para a 
  //variavel msg
  con.connect(function(err) {
       con.query('SELECT * FROM dados', function(err, rows, fields) {
           if (err) throw err;
                 msg = rows;
       });
    });

then that is, when the program is run, it brings the empty msg variable. Thank you very much!

1 answer

0

Study asynchrony on Ode and its relationship with callbacks. The code is not running in the sequence you are thinking of.

let msg =[];  

io.on('connection', socket => {

    con.connect(function(err) {

        con.query('SELECT * FROM dados', function(err, rows, fields) {
            if (err) throw err;
            // [1]
            msg = rows;
            socket.emit('msg_existentes',msg);
        });

    });

});
  • Leandro, face this way, Cod loops and is giving a warnings websocket.js:234 WebSocket connection to 'ws://localhost:3001/socket.io/?EIO=3&transport=websocket&sid=v_OEjrUil-xkVarwAABm' failed: WebSocket is closed before the connection is established.

  • @Fabriciocarneiro this is already another error, which can be caused by other reasons.

  • @Leandro, man I studied more deeply and I understood the kkk cacas, man it worked out, thank you so much for the strength bro.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.