Real-time website with Node.JS

Asked

Viewed 176 times

-2

Come on, guys, can someone help me with this...

I developed a fully dynamic website with Mysql database, that is, all the main elements of the main page are coming from the database, I do this using Node.JS, Express and Mysql.

The problem is that after changing something in the database, even updating the page (F5) the screen information does not change. The change only reflects on the page if I restart the service "nodemon app.js" by CMD.

I’ve done a lot of research on the subject and arrived in Socket.io, I was able to start it here in my application, but I’m not able to use it to update the queries to Mysql.

See the main excerpts of my code structure related to this theme, please help me:

Excerpt from the archive app js.

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

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

var port = 3000;
io.on('connection', function (io) {
http.listen(port, () => {
    console.log('Em execução');
    console.log('Endereço do site : localhost:', port);
});

//Aqui está minha rota onde faço as consultas
const rotas = require('./routes/rotas')(io);
app.use('/', rotas);

So far so good.

We now go to the route archive: Excerpt from the archive js routes.

module.exports = (io) => {//Aqui recebo o socket.io lá do app.js

var express = require('express');
var rotas = express.Router();

const { pageSite } = require('../controller/site/site.js'(io); //Aqui passo o socket.io para o site.js
rotas.get('/', pageSite); //localhost:3000 (rota da página principal)

return rotas;
};

So far so good.

We go now to the file that makes the render of the main page of the site: Excerpt from the archive site js.

//Aqui importo o site-model onde tem minhas consultas SQL
const funcao = require('./site-model');

//Aqui pego o resultado da consulta e gravo na variável section1
let section1;
(async function () {
   section1 = JSON.parse(JSON.stringify(await funcao.getSection1_Title));
})()

//Aqui passo os dados da variável section1 como parâmetro para o render da página
module.exports = (io) => {
   return {
      pageSite: (req, res, next) => {
         res.render('./site/index', {
             DTSection1: section1
         });
      },
   };
}

So far so good.

We now go to the file that makes the queries used by render: Excerpt from the archive site-model.js

//Função para consuoltar no banco
function select(query) {
    return new Promise((resolve, reject) => {
        conn.query(query, function (err, rows, fields) {
            if (err) return reject(err)
            resolve(rows);
        });
    });
}
module.exports = {
getSection1: (async function () {
        const result = await select('SELECT * FROM tb_section1 ORDER BY cod DESC');
        return result;
    })(),
}

So far so good.

Everything is working perfectly, whenever I update something in the comic book it reflects on the page provided I restart the Node service in CMD.

HELP: Only I need the data to be updated on the page when I give "F5" on the page.

I think that when updating the page socket.io should reprocess the BD query by rewriting the new return in the "section1" variable of the site.js file, but how to do this?

Note: Reinforcement that on the page yield step 22 variables that received 22 queries from 22 different tables.

  • I don’t see why you need Socketsio, the problem you’re describing doesn’t need Sockets to solve. You can explain better one of the routes I wasn’t updating and all the code that it runs?

  • For me the problem is that you use predecessors, if you use only calls to the server without Promise, you solve your problem, things are updated only with F5.

1 answer

1

It doesn’t reflect when updating the pq page you’re taking the data when the app starts. see:


// isso é executado apenas uma vez, assim que o arquivo é importado
let section1;
(async function () {
   section1 = JSON.parse(JSON.stringify(await funcao.getSection1_Title));
})()

// sempre que esse rota e chamada vc pega o valor que esta em memoria
module.exports = (io) => {
   return {
      pageSite: (req, res, next) => {
         res.render('./site/index', {
             DTSection1: section1
         });
      },
   };
}

for it to work correcting the code should be so:

// ...
function getSection1_Title() {
        return select('SELECT * FROM tb_section1 ORDER BY cod DESC');
}

// ...

module.exports = (io) => {
   return {
      pageSite: async (req, res, next) => {
         res.render('./site/index', {
             DTSection1: await getSection1_Title()
         });
      },
   };
}

So note for some reason you are using auto invoked functions: (() => {})() I don’t know why you’re doing this, it doesn’t make any sense to use in this context finds.

  • It speaks Galera, I tried all the suggested possibilities and still without success, I am new in the WEB programming and I am picking up a bit, I put the source code in 4shared, want to have a look if they can solve please: https://www.4shared.com/zip/yLetNq92iq/CCF.html

  • @Fabioeduardoargenton Matheus' answer points to flaws in the knowledge of asynchronous code chaining. That’s what I was telling you in my comment (which you didn’t even answer). You understood the way Matheus said?

  • Guys, thank you all, I really appreciate the help, but I managed to solve, tint the same code and only added a snippet before the render, see: pageSite: (req, res, next) => { //This snippet here was the solution Conn.query('SELECT * FROM section_1_title ORDER BY Cod DESC LIMIT 1', Function (err, Rows, Fields) { if (err) throw err; section1 = JSON.parse(JSON.stringify(Rows));//Here re-query }); Note: Someone has closed the thread now I cannot post the complete solution.

Browser other questions tagged

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