SELECT * FROM with Node and socket.io

Asked

Viewed 138 times

1

Good morning guys, I’d like to know how I can make one select on the bench with Nodejs, using the socket.io.

In the code below I show the commented line, where it is to be the select, but it does not return the data to the variable msg.

    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('/', ( req , res ) => {
            req.render('index.html');
        });

        let msg =[];  

            //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;
            //     });
            // });


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

        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);
No answers

Browser other questions tagged

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