Refresh page when making BD changes

Asked

Viewed 38 times

0

Goal

My final project involves making a chat room; the user must enter a message, this message is handled in the server.js(Node.js file) and inserted into the database. The page should then be updated with each insertion and display old and new messages.

my chat was based on this here.

What has been done

The html of the chat page:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>

</head>
<body>
    <form action="/chat" method="POST">
        <div class="messages" id = "messages"></div>
        <input type="text" id="message" name="message" placeholder="Digite sua mensagem">
        <input type="submit" value="Enviar"> 
    </form>

    
    <script type="text/javascript"> 
      
    // Conecta no servidor
    var socket = io('http://localhost:3000');

    // Renderiza a mensagem na DIV
    function renderMessage(message) {
       $('.messages').append('<div class="message"><strong>'+ message.author +'</strong>: '+ message.message +'</div>');
    }

    // Recebe as mensagens anteriores
    socket.on('previousMessages', function(messages) {
       for (message of messages) {
            renderMessage(message);
        }
    });

    // Recebe a Mensagem e chama o renderizador
    socket.on('receivedMessage', function(message) {
        renderMessage(message);
        console.log(username);
    });

    // Verifica quando é enviado uma mensagem
    $('#chat').submit(function(event) {
       event.preventDefault();

       var author = "<%= username %>";
       console.log(author)
       var message = $('input[name=message]').val();

       if (message.length) {
           var messageObject = {
               author: author,
               message: message,
           };

           // Renderiza a mensagem
           renderMessage(messageObject);

           

           // Envia a mensagem para o socket no Back-End
           socket.emit('sendMessage', messageObject);
       }
    });

    </script>
</body>

As you can see I insert these messages into the div "messages". Now the server.js file:

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

app.get('/public/chat.html', (req, res) => {
    res.render('chat.html');
});

app.get('/public/sign_up.html', (req, res) => {
    res.render('sign_up.html');
});

var connection = mysql.createConnection({
    host:'*****',
    user: '*****',
    password: '', 
    database: '*****'
});

connection.connect(function(error) {
    if(!!error){
        console.log('Error!')
    }
    else{
        console.log('Connected')
    }

    //Ao ligar o servidor, as mensagens antigas são apresentadas

    connection.query('SELECT * FROM chat', function(err, rows, fields) {
        if (err) throw err;
            let data = new Object();
            for(var i = 0; i < rows.length; i++) {
                data.author = rows[i].nickname;':';
                data.message = rows[i].msg;
                messages.push(JSON.parse(JSON.stringify(data)));
                console.log(data);
            }
            console.log(messages);
    });
});

app.post('/chat', function(request, response) {
    var nickname = "User"
    var message = "teste"
    console.log(message);
    console.log(nickname);
    if (message) {
        connection.query('INSERT INTO chat (nickname, msg) VALUES (?, ?)', [nickname, message], function(error, results, fields) {
            response.redirect(request.get('referer'));
        });
    }
});

let messages = [];

io.on('connection', socket => {
 console.log(`Socket conectado: ${socket.id}`);

 socket.emit('previousMessages', messages);

 socket.on('sendMessage', data => {
    messages.push(data);
    socket.broadcast.emit('receivedMessage', data);
 });
});

server.listen(3000);

Problems

Basically two problems:

  • how to efficiently display the received data page?
  • I realized that restarting the page is not enough, because the new messages are only shown when restarting the Node server

1 answer

0

I solved this problem by entering it into the database using the.IO socket instead of using the express routes:

socket.on('sendMessage', ({ author, message }) => {
    connection.query('INSERT INTO chat (nickname,msg) VALUES (?, ?)', [author, message], function(error, results, fields) {
    });

Then I gave an Emit in the new messages:

messages.push({ author, message })
    socket.broadcast.emit('receivedMessage', ({ author, message }));

And I performed at the front end:

socket.on('receivedMessage', function(messages){
      renderMessage(message);
    }); 

Browser other questions tagged

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