0

I'm working on a node.js app that tries to fetch data from a socket.io client to populate a response to a POST request from another client. Something like...

  1. POST http request from client A
  2. server requests data over socket.io from client B
  3. client B returns data over socket to server
  4. server responds to client A

Client A, making the initial POST request, is a web service (Plivo/plivo-node) so I can't change how it hits the server.

The node code which is called on the POST request looks like this...

app.handlePlivoRequest = function (req, res) {

    // create Plivo response object
    var r = plivo.Response();

    // set listener for client response
    client.socket.on('callResponse', function(msg){

        // add msg data from client to the Plivo response
        r.addSpeak(msg);
    });

    // forward request to socket client
    client.socket.emit('call', req.body );

    // render response as XML for Plivo
    return r.toXML();

}

The problem I have is that handlePlivoRequest returns without waiting for the response from the client.

Can anyone help with how I'd re-factor this to wait for the socket to respond?

Thanks!

bt-nick
  • 1
  • 2

1 Answers1

0

You need to end the http request inside the socket response callback:

app.handlePlivoRequest = function (req, res) {

// create Plivo response object
var r = plivo.Response();

// set listener for client response
client.socket.on('callResponse', function(msg){

    // add msg data from client to the Plivo response
    r.addSpeak(msg);

    // render response as XML for Plivo
    res.set({ 'Content-Type' : 'text/xml'});
    res.end(r.toXML());
});

// forward request to socket client and wait for a response..
client.socket.emit('call', req.body );

}

DanB
  • 1,060
  • 7
  • 13