Reputation: 93
I'm trying to create an API that sends an information obtained by a socket.
To get the information from my socket, I'm using zmq.
The idea is when got the information from the socket, send this info as a response in my API. The following code pretends do that.
[...]
enclaveSocket.on('message', function (message) {
res_json.info = message.toString('base64');
res.json(res_json);
});
enclaveSocket.send('chesf:public');
[...]
In the first request to my express API, the return is the expected:
{
"organization": "my_org",
"info": "AjCWyQeBNeuMnA3nAUrbprxctrdOgZmjDR5Rmuw6LzzMpALspfNapLMoRGPx9YEGFrqrE5vdHKPb/z0S23i8v"
}
But in the second request my API crashes with the following error:
events.js:160
throw er; // Unhandled 'error' event
^
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:367:11)
at ServerResponse.header (/home/matteus/keyvault-node/node_modules/express/lib/response.js:725:10)
at ServerResponse.send (/home/matteus/keyvault-node/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/matteus/keyvault-node/node_modules/express/lib/response.js:256:15)
at exports.Socket.<anonymous> (/home/matteus/keyvault-node/routes/keys.js:58:21)
at emitOne (events.js:101:20)
at exports.Socket.emit (events.js:188:7)
at exports.Socket.Socket._flushRead (/home/matteus/keyvault-node/node_modules/zmq/lib/index.js:636:10)
at exports.Socket.Socket._flushReads (/home/matteus/keyvault-node/node_modules/zmq/lib/index.js:676:23)
at Object._zmq.onReadReady (/home/matteus/keyvault-node/node_modules/zmq/lib/index.js:297:10)
That's it.
Upvotes: 0
Views: 139
Reputation: 93
I solved my problem using enclaveSocket.once()
instead of enclaveSocket.on()
.
The once()
method removes event listeners when the event is handled by the same function.
More information about here: http://nodeguide.com/beginner.html#using-eventemitters
Upvotes: 1