Why Does Server Crash On Second Request?
I have a nodejs server as shown below. The server is able to set headers when the res.header() statement is not inside a event. It fails when it is executed in resposne to an event like so:
app.get('/m/ad', function (req, res) {
adManager.on('ad_unit_exists', function (ad_unit) {
res.header('Ad-Type',"html");
res.end();
return;
});
adManager.emit('ad_unit_exists',{});
});
Edit: Fa开发者_高级运维ils meaning, the server crashes with the following error:
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:526:11)
at ServerResponse.setHeader (/home/raj/node_modules/express/node_modules/connect/lib/patch.js:44:20)
at ServerResponse.header (/home/raj/node_modules/express/lib/response.js:242:10)
at EventEmitter.<anonymous> (/home/raj/Projects/adreactor-node/server.js:227:28)
at EventEmitter.emit (events.js:81:20)
at Object.<anonymous> (/home/raj/Projects/adreactor-node/server.js:232:16)
at nextMiddleware (/home/raj/node_modules/express/lib/router/index.js:139:34)
at param (/home/raj/node_modules/express/lib/router/index.js:147:16)
at pass (/home/raj/node_modules/express/lib/router/index.js:155:10)
at Object.router [as handle] (/home/raj/node_modules/express/lib/router/index.js:161:6)
Why do you think this is?
EDIT: The requests works perfectly for the first request. The server crashes on the second request.
The adManager variable is a global variable. For some reason it stores the arguments to the event handlers.
I was using adManager as a sort of global EventEmitter object for emitting events and managing the flow of code.
I had an additional statement outside like so that initializes adManager on server start:
app.get('/m/ad', function (req, res) {
adManager.on('ad_unit_exists', function (ad_unit, req, res) {
res.header('Ad-Type',"html");
res.end();
return;
});
adManager.emit('ad_unit_exists',{}, req, res);
});
AdManager.prootype = new process.EventEmitter();
var adManager = new AdManager();
The res
in the callback for the ad_unit_exists event was being parsed the res from the previous event emission - the previous request that had already end()'ed - when the event was emitted for the second request. Strange.
Solved it by adding :
adManager = new AdManager()
within the app.get() callback function.
I don't think this code can give us a complete picture(function incomplete?). The error tells us you are writing to the socket two times. Probably res.end()
gets called two times instead of just one time. You should put some debugging statements(console.log
) in between to get a better picture.
精彩评论