KC32 KC32 - 6 months ago 61
Node.js Question

NodeJS: Error with multiple GET requests

I am working on a web app, where I have a database with data for games, and I make a GET request to an API when you click on any game. I want my app to work so that you can click on any one game and you will be able to populate the page for that game with the extra information from the request without having to do the GET requests upfront for every single game (about 200), but I am having the following issue:

_http_outgoing.js:344
throw new Error('Can\'t set headers after they are sent.');
^

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (C:prototype\node_modules\express\lib\response.js:718:10)
at ServerResponse.send (C:prototype\node_modules\express\lib\response.js:163:12)
at ServerResponse.json (C:prototype\node_modules\express\lib\response.js:249:15)
at EventEmitter.<anonymous> (C: prototype\webapp.js:182:14)
at emitNone (events.js:72:20)
at EventEmitter.emit (events.js:166:7)
at IncomingMessage.<anonymous> (C:webapp.js:237:17)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:913:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)


Here is the code that I am trying to run:

req = https.request(options, function(res) {
var responseBody ="";
res.setEncoding("UTF-8");
//retrieve the data in chunks
res.on("data", function(chunk) {
responseBody += chunk;
});

res.on("end", function(){
//Once completed we parse the data in JSON format
sendData = JSON.parse(responseBody);
console.log(sendData);
eventEmitter.emit('got_data');
});
});

req.on("error", function(err) {
console.log(`problem with request: ${err.message}`);
});
req.end();


and here is the routing for it:

app.get('/api/gameDetails', function(req, res) {
var device = req.query.device;
var id = req.query.id;
requestForGameDetails(id, device);
eventEmitter.on('got_data', function() {
return res.json(sendData);
});
});

Answer

you are getting the error because you are using eventEmitter.on which continuously listens for the event and in turn sends results multiple times. since you can only send one response you need to use eventEmitter.once which will remove the listener after the first event.