nodejs auto refresh view after database updates

前端 未结 1 1602
囚心锁ツ
囚心锁ツ 2021-02-04 19:38

I would like use nodeJS to refresh my view, every time a function has made changes to the database. If we take MEAN-stack as an example, I don\'t want to send an $http-request e

相关标签:
1条回答
  • 2021-02-04 20:15

    To get the front end to get notified automatically and then update the view you could use Socket.io framework. You can find all of the documentation on their site: http://socket.io/ And here is a basic example:

    app.js ( to set up the server)

    var http = require('http');
    var express = require('express');
    var port = normalizePort(process.env.PORT || '1000');
    var app = express();
    var server = http.createServer(app);
    server.listen(port);
    
    io = require('socket.io')(server);
    
    ///ROUTES
    var routes = require('./routes/index')(io);
    var users = require('./routes/users');
    ///////
    

    I pass the io object to route index(and ofcourse there is a lot more stuff on app.js..this is just a basic example...).

    mysql.js (to create a pool for connections)

    var mysql = require("mysql");
    var pool = mysql.createPool({
    host     : 'host',
    user     : 'user',
    password : 'pass',
    database : 'db_name',
    connectionLimit: 1000
    });
    
    exports.pool = pool;
    

    index.js

    module.exports = function(io) {
     var express = require('express');
     var router = express.Router();
     var mysql = require('../mysql.js').pool;
    
     io.on('connection', function (socket) {
            socket.on('event_name', function (data) {
        mysql.getConnection(function(err,connection){
            if (err) {
              connection.release();
              return;
            }               
             connection.query("SQL STUFF",function(err,rows){
                if(rows.length>0){//checks if there are more than 0 rows returned.....
                    socket.emit('do_something',data_you_want_to_pass);
                }
                else{
                    socket.emit('do_something_else',data_you_want_to_pass);
                }
                connection.release();    
             });
    
              connection.on('error', function(err) {      
                return;    
              });
        });
      });
    
    });
    
    router.get('/', function(req, res) {
    res.render("index"); 
    });
    
    return router;
    }
    

    And then on html page you have socket.emit and socket.on again.....

    I recommend you take a look at the documentation and a few other examples...

    I hope I helped you.

    0 讨论(0)
提交回复
热议问题