简体   繁体   中英

how to show real-time data using node.js, socket.io and mysql?

I am new to Node.js and trying to show real-time data to a web-page. What I try to do is first I insert into MySQL database via an URL. This is URL [ http://localhost:4000/api/motor_details?deviceId=145&a=sdfa3&b=us&c=uds] . Below code is able to insert into the database. The data is visible only refreshing the page but I want to see inserted data to my web-page without refreshing it.
This is my index.js (Main File)

<pre>
var express = require('express');
    var socket = require('socket.io');
    var mysql = require('mysql');
    var http = require("http");
    var app = express();
    var server = app.listen(4000,function(){
        console.log('Listening 4000');
    });
    var io = socket(server);
    app.use(express.static('public'));

    var connectSql = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "root",
        database: "grid_component",
        socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
    });
    connectSql.connect();
    app.get('/api/motor_details', function(req, res) {
        var device_id = req.param('deviceId');
        var a = req.param('a');
        var b = req.param('b');  
        var c = req.param('c');  
        var entries = {
            device_id: device_id,
            a: a,
            b: b,
            c: c,
            date: '2018-06-27'
        }
        var query = connectSql.query('insert into entries set ?', entries,function (err, result) {
            if(err){
                console.error(err);
                return;
            }  
        })
    });
    io.on('connection',function(socket){
        connectSql.query('SELECT * FROM entries',function(err,rows){
            if(err) throw err;
            socket.emit('showrows', rows);
        });
    });
</pre>

<pre>
var socket = io.connect('http://localhost:4000');
 socket.emit('showrows');
 socket.on('showrows', function(rows) {
     var html='';
     for(var i=0; i<rows.length; i++){
         html += rows[i].device_id + ' ' + rows[i].a + '<br>';
     }  
     document.getElementById("display").innerHTML = html;
 }); 
</pre>

[![Error Screenshot][1]][1]

I even tried to change the req.param with req.params, req.body or req.query but its showed undefined

Because you are using a query string for parameters [ http://localhost:4000/api/motor_details?deviceId=145&a=sdfa3&b=us&c=uds] instead of route based parameters [ http://localhost:4000/api/motor_details/145/sdfa3/us/uds] , you should use req.query instead of req.params or req.route.

In Express 4+, you will want to use req.query.name-of-parameter instead of req.query('deviceId') https://expressjs.com/en/api.html#req.query

After getting data into the database, you will want to emit an event through socket.io from your node server to your client web page to tell it to retrieve the data.

var express = require('express');
var socket = require('socket.io');
var mysql = require('mysql');
var http = require("http");
var app = express();
var server = app.listen(4000,function(){
    console.log('Listening 4000');
});
var io = socket(server);
app.use(express.static('public'));

var connectSql = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "grid_component",
    socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
connectSql.connect();
app.get('/api/motor_details', function(req, res) {
    var device_id = req.query.deviceId;
    var a = req.query.a;
    var b = req.query.b;  
    var c = req.query.c;  
    var entries = {
        device_id: device_id,
        a: a,
        b: b,
        c: c,
        date: '2018-06-27'
    }
    var query = connectSql.query('insert into entries set ?', entries,function (err, result) {
        if(err){
            console.error(err);
            return;
        }  
    })
    //emit using socket io, you can name it whatever you want
    socket.emit('sendingMessage');
});

//set up route to retrieve motor details
app.get('/api/get-motor-details', function(req, res) {

    var query = connectSql.query('SELECT * FROM entries',function(err,rows){
        if(err) throw err;
        res.end(JSON.stringify(rows);
    });
});

//all this is doing is telling the server to retrieve the data upon every socket connection, which is not the behavior you wanted
/*io.on('connection',function(socket){
    connectSql.query('SELECT * FROM entries',function(err,rows){
        if(err) throw err;
        socket.emit('showrows', rows);
    });
});*/


//-----------------CLIENT--------------------------
/*on your client webpage you will need to set up socket.io and a listener for 
the sendingMessage event*/
var socket = io('http://localhost:4000');
socket.on('sendingMessage', () => {
    //use whatever library you want for ajax calls, this is just an example
    fetch('http://localhost:4000/api/get-motor-details')
    .then((response) => {
        var html='';
        for(var i=0; i<response.length; i++){
            html += response[i].device_id + ' ' + response[i].a + '<br>';
        }  
        document.getElementById("display").innerHTML = html;
    });
});

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