nodejs auto refresh view after database updates

不打扰是莪最后的温柔 提交于 2021-01-20 16:56:42

问题


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 every x seconds to check if changes have been made to the database. I would like the front end to get notified automatically and then update the view.

What are best practices for this? I would use some kind of Oberserver pattern in the server side, but do not know how I could notify the front end with that.


回答1:


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.



来源:https://stackoverflow.com/questions/35024814/nodejs-auto-refresh-view-after-database-updates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!