Ad

Send Message Stream To View Using Express Js And Socket.io

- 1 answer

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?

Ad

Answer

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)
Ad
source: stackoverflow.com
Ad