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...
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!
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 );
}