简体   繁体   中英

send message stream to view using express js and socket.io

I have the following nodejs/express js

/* GET home page. */
router.get('/', function(req, res, next) {

  socket.on(channelName, message => { 
    //console.log(channelName, message);
  });

  res.render('index', {page:message, menuId:channelName});
});

How can I pass the message it was the real time data to display in index view?

In the route method, you will need to fire/emit the event, so for example
when a message hit this route all the listeners on the 'message'
will call the Action :

app.post('/messages', (req, res) => {
  var message = new Message(req.body);
  message.save((err) =>{
    if(err)
      sendStatus(500);
    io.emit('message', req.body);
    res.sendStatus(200);
  })
})

And in the client side script tag in index.html, add the following code:

var socket = io();

socket.on(‘message’, addMessages)

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