简体   繁体   中英

NodeJS socket.io show data from MySQL realtime

I'm working on NodeJS and socket.io .

The current function is working good to display data from mysql database to table.
Now I need the page view auto update/refresh (realtime) if there is a new data received.

Here is the HTML

<div id="display"> </div>
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.on('connect', function() {
    document.getElementById("socketio").innerHTML = "socket connected";
  });
  socket.on('showrows', function(rows) {
    var html='';
    for (var i=0; i<rows.length; i++) {
      html += rows[i].product_name + ' ' + rows[i].product_price + '<br>';
    }  
    document.getElementById("display").innerHTML = html;
    console.log(rows);
  });
</script>

and index.js

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

app.get('/', function(req, res){
  res.sendfile('testsql.html');
  //res.sendfile('/login/');
});
http.listen(3000, function(){
  console.log('listening on *:3000');
});
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "crud_db"
});

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

    console.log('a client connected');

    con.query('SELECT * FROM product',function(err,rows){
      if(err) throw err;
      console.log('Data received from Db:\n');
      console.log(rows);
      socket.emit('showrows', rows);
    });
 });

My question, how to make a realtime function to web page if there is a new data received?

I never try it before, but I think you can do something like this

1.first listen an event when there is new submitted data

io.on('connection', function (socket) {
    socket.on('new data', function (data) {
       socket.emit('broadcast', data) // send it to the client
    })
})

2.store the io instance to app.locals:

app.locals.io = io

3.then, consider you have an endpoint to create a new data:

app.post('/product', function (req, res) {
    const sql = `INSERT INTO products (name, price) VALUES (${req.body.name}, 
    ${req.body.price})`
    
    con.query(sql, function (err, result) {
        if (err) throw err;
        const io = req.app.locals.io
        io.emit('new data', { data: result })
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM