-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
What do you want done when a registration is made? Is it to call some function? To update some part of the page?
– tvdias
That’s right I want only the parent element to update and show the result without being the full page to each new registto
– Teuuz1994
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.
– tvdias
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?
– Teuuz1994
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.
– tvdias
When I refer to "refresh the page" I am referring to a part of the page, such as a div.
– tvdias
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
– Teuuz1994
If the answer was helpful, don’t forget to vote up and mark as accepted.
– tvdias
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.
– tvdias
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...
– tvdias
I edited the answer
– tvdias
Was able to verify the answer?
– tvdias
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
– Teuuz1994
Can you verify the answer? Don’t forget to accept it if you are satisfied with it.
– tvdias