POST data through socket.io to app.js


Question

I would like to:

  • retrieve data entered from input forms.
  • send the data through socket.io and send console log saying done
  • receive the data on express app.js
  • insert the data into a mongodb database using mongoose.

I understand emit messages but not sure how to post data through. thank you in advance

my app.js is set up like this:

//app.js config ...

var socket = io.listen(server);

socket.on('connection', function(socket) {
   console.log('socket.io connected');
});



app.post('/go', function(req, res) {

  socket.on('data', function(data) {
    new Order({
      routeFrom : data.routeFrom,
      routeTo : data.routeTo,
      leaving: data.leaving
    }).save(function(err, docs) {
      if(err) { console.log("error"); }
      res.json(data);
    });
    socket.emit('callback', {done: 'Done'});
  });

});

my index.ejs file:

  <script src="/socket.io/socket.io.js"></script>

 var socket = io.connect('http://localhost:3000');

$('#send').on('click', function() {
    $.post('/go', {
       socket.emit('data', {
        routeFrom: $('#rf').val(),
        routeTo: $('#rt').val(),
        leaving: $('#l').val()
       });

    });

  socket.on('callback', function(data) {
   console.log(data);
  });

});

1
7
12/10/2012 2:16:23 PM

Accepted Answer

You don't need POST at all.

I would do on the client side:

var socket = io.connect('http://localhost:3000');

$('#send').on('click', function(event) {
  event.preventDefault();
  socket.emit('data', {
    routeFrom: $('#rf').val(),
    routeTo: $('#rt').val(),
    leaving: $('#l').val()
  });
});

socket.on('callback', function(data) {
  console.log(data.done);
  // Print the data.data somewhere...
});

And on the server side:

//app.js config ...
var socket = io.listen(server);

socket.on('connection', function(socket) {
  console.log('socket.io connected');
});

socket.on('data', function(data) {
  new Order({
    routeFrom : data.routeFrom,
    routeTo : data.routeTo,
    leaving: data.leaving
  }).save(function(err, docs) {
    if(err) { return console.log("error"); }
    socket.emit('callback', {done: 'Done', data: data});
  });
});
13
12/10/2012 4:06:01 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon