how to receive data dynamically via websocket?

Asked

Viewed 228 times

-1

I’m trying to update a <div> which is receiving data from the database in a dynamic way, however, I tried to implement this way and even so remains wrong and do not know where I’m going wrong, I will leave the source code below separated by files.

main file (app.js):

const express = require('express');
const app = express();
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const porta = process.env.PORT || 3000
const Usuario = require('./models/Usuario');
const admin = require('./routes/admin')


//configurando segurança do app
app.use(helmet());
//session
//configurar aqui!
//template engine
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//public
app.use(express.static(path.join(__dirname, 'public')))
//socket.io
var gettingDados = Usuario.findAll({ limit: 1, order: [['id', 'desc']] })


io.on('connection', function(socket) {
    console.log(`usuarios ${socket.id} conectado!`)
    io.emit('data_getting', gettingDados)
    socket.on('data_getting', function(msg){
        let i = 0; i < usuarios.length; i++
        io.emit('data_getting', gettingDados)
        console.log('mensagem recebida', msg)
    })

})
//rotas
app.get('/', (req, res) =>{
    res.render('index')
})


app.use
app.use('/admin', admin)

http.listen(porta, () => {
    console.log(`servidor rodando na url http://localhost:${porta}`);
})

registration page(registration.ejs):

<% for( let i = 0; i < usuarios.length; i++ ) { %>
<div id="relatorio">
    <small id="id">id: <strong><%- usuarios[i].id %></strong></small><br>
    <small id="nome">Nome: <strong><%- usuarios[i].nome %></strong></small><br>
    <small id="email">Email: <strong><%- usuarios[i].email %></strong></small><br>
    <small id="senha">Senha: <strong><%- usuarios[i].senha %></strong></small><br>
</div>
<hr><% } %>

<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
    var socket = io();

    socket.on('listen', )

    socket.on('data_getting', function(msg){
        document.getElementById('relatorio').innerHTML = msg
    });
</script>

and finally the route that sends the queries in the bank to this page

registro(router/admin.js):
const express = require('express')
const router = express.Router()
const Usuario = require('../models/Usuario')

router.get('/cadastro', (req, res) => {
    res.render('admin/cadastro')
})

router.post('/cadastro', (req, res) => {
    Usuario.create({
        nome: req.body.nome,
        email: req.body.email,
        senha: req.body.senha
    }).then(() => {
        res.send('usuário cadastrado com sucesso!')
    }).catch((err) => {
        res.send('não foi possível cadastrar novo usuário' + err)
    })
})

router.get('/registro', (req, res) => {
    Usuario.findAll({ limit: 1, order: [['id', 'desc']] }).then((usuarios) => {
        res.render('admin/registro', {usuarios:usuarios})
    })
})

module.exports = router

the result that appears is as follows: resultado do websocket

  • What do you want done when a registration is made? Is it to call some function? To update some part of the page?

  • That’s right I want only the parent element to update and show the result without being the full page to each new registto

  • That being the case, add the part of HTML that should be updated and what you expect to appear in the case of an event.

  • I understood the theory the problem is the implementation I’m implementing wrong, is that I’m new in programming so in some things I curl up, would you show me a practical example friend? Based on the same condition I quoted?

  • This requires you to add your HTML and what you want to do. There are numerous ways to create notifications, if that’s what you want to do. If you want to simply refresh the page, you need to know it.

  • When I refer to "refresh the page" I am referring to a part of the page, such as a div.

  • I understood friend anyway I will try to implement after I send the result here msm so thank you for the help you gave me an idea that can work, at least in theory

  • If the answer was helpful, don’t forget to vote up and mark as accepted.

  • Remember to always include in the question all the information and add all the related code, so people know what has been tried and point out where it can change.

  • With the edits it is possible to see that you did not understand how and when to use websockets. I will edit the answer to include more parts of your code and try to explain the problems...

  • I edited the answer

  • Was able to verify the answer?

  • Sorry friend took so long to answer, actually who is seeing this part of the code is another guy just put here what I tried to do and had not even seen your answer because we are trying to do a project and I will see with him and as soon as can put here

  • Can you verify the answer? Don’t forget to accept it if you are satisfied with it.

Show 9 more comments

1 answer

0

From what I’ve been presented, I’d say doubt is just like "getting started". The best way would be to look at the Socket.IO documentation and try to apply "Getting Started" to your project. However, what was presented is not a good example to demonstrate the use of Socket.IO, since it is only a user registration.

How to initialize the backend

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});

When it is necessary to send an event to the frontend:

io.emit('NOME_DO_EVENTO', "mensagem...");

to update the frontend

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script>
      $(function () {
        var socket = io();
        socket.on('NOME_DO_EVENTO', function(msg){
          // AÇÕES NO FRONTEND
        });
      });
    </script>
  </body>
</html>

EDITED: the excerpt below has been added to use the code presented in the question. Changes to be made:

  • No need to launch events when loading the page, so part of the code was commented on app.js
  • Launches event when registering a user
  • Catch the event on the frontend and update the div report (note that other HTML fixes are still needed, which are outside the scope of the question)

app js.

const express = require('express');
const app = express();
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const porta = process.env.PORT || 3000
const Usuario = require('./models/Usuario');
const admin = require('./routes/admin')


//configurando segurança do app
app.use(helmet());
//session
//configurar aqui!
//template engine
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//public
app.use(express.static(path.join(__dirname, 'public')))

//socket.io
// código abaixo não é necessário
//var gettingDados = Usuario.findAll({ limit: 1, order: [['id', 'desc']] })

io.on('connection', function(socket) {
// código abaixo não é necessário
//    console.log(`usuarios ${socket.id} conectado!`)
//    io.emit('data_getting', gettingDados)
//    socket.on('data_getting', function(msg){
//        let i = 0; i < usuarios.length; i++
//        io.emit('data_getting', gettingDados)
//        console.log('mensagem recebida', msg)
//    })
})

//rotas
app.get('/', (req, res) =>{
    res.render('index')
})


app.use
app.use('/admin', admin)

http.listen(porta, () => {
    console.log(`servidor rodando na url http://localhost:${porta}`);
})

Register

registro(router/admin.js):
const express = require('express')
const router = express.Router()
const Usuario = require('../models/Usuario')

router.get('/cadastro', (req, res) => {
    res.render('admin/cadastro')
})

router.post('/cadastro', (req, res) => {
    Usuario.create({
        nome: req.body.nome,
        email: req.body.email,
        senha: req.body.senha
    }).then(() => {
        io.emit('new_user', {nome: req.body.nome, email: req.body.email})
        res.send('usuário cadastrado com sucesso!')
    }).catch((err) => {
        res.send('não foi possível cadastrar novo usuário' + err)
    })
})

router.get('/registro', (req, res) => {
    Usuario.findAll({ limit: 1, order: [['id', 'desc']] }).then((usuarios) => {
        res.render('admin/registro', {usuarios:usuarios})
    })
})

module.exports = router

registration ejs.:

<% for( let i = 0; i < usuarios.length; i++ ) { %>
<div id="relatorio">
    <small id="id">id: <strong><%- usuarios[i].id %></strong></small><br>
    <small id="nome">Nome: <strong><%- usuarios[i].nome %></strong></small><br>
    <small id="email">Email: <strong><%- usuarios[i].email %></strong></small><br>
    <small id="senha">Senha: <strong><%- usuarios[i].senha %></strong></small><br>
</div>
<hr><% } %>

<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
  var socket = io();
  socket.on('new_user', function(msg){
    // AÇÕES NO FRONTEND
    // AQUI DEVERIA SER FEITO ALGO PARA ADICIONAR O NOVO USUÁRIO À LISTA DE USUÁRIOS
    // ENTRETANTO, O SEU HTML NÃO ESTÁ FEITO CORRETAMENTE
    // POR ISSO, O CÓDIGO ABAIXO SUBSTITUIRÁ AS INFORMAÇÕES DA DIV relatorio
    document.getElementById('relatorio').innerHTML = "Usuário " + msg.nome + " adicionado."
  });
});
</script>
  • I may not have been very clear on my question but come on, what I actually want is to monitor this route of records every time you have a new user it shows on the screen without updating the whole page I can only implement in Webchat out of it I couldn’t, I’d like a way

  • So improve your question, be more objective. Ta very large and I thought the answer would be correct for your question .

Browser other questions tagged

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