简体   繁体   English

NodeJS socket.io 实时显示来自 MySQL 的数据

[英]NodeJS socket.io show data from MySQL realtime

I'm working on NodeJS and socket.io .我正在研究NodeJSsocket.io

The current function is working good to display data from mysql database to table.当前的 function 可以很好地将 mysql 数据库中的数据显示到表中。
Now I need the page view auto update/refresh (realtime) if there is a new data received.现在,如果收到新数据,我需要页面视图自动更新/刷新(实时)。

Here is the HTML这是 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.jsindex.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?我的问题,如果收到新数据,如何制作实时 function 到 web 页面?

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 1.当有新提交的数据时首先监听一个事件

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: 2.将io实例存储到app.locals:

app.locals.io = io

3.then, consider you have an endpoint to create a new data: 3.then,考虑你有一个端点来创建一个新数据:

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 })
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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