I am initiating a node js web server with restify module.
server = restify.createServer();
server.post('/getData', DataManager.getData);
Handler for /getData path looks like this:-
DataManager.prototype.getData = function(request, response, next) {
var body = JSON.parse(request.body);
var key = body.key;
callback = function(err, instance) {
if(!err && instance) {
response.send(instance);
}
else {
response.send('err');
}
return next();
}
MongooseModel.findOne(key, callback);
}
When I shoot 2 concurrent requests to /getData with different payloads, the server throws [Error: Can't set headers after they are sent.] error and doesn't respond to the second request.
I am looking for a remedy to this.
--
I think, restify treats DataManager.getData as a static function. Instead of serving each request to /getData with a new object of DataManager it is using single static instance of it. While the first request is still executing as per nodejs, the second request tries to send a response which is why nodejs says can't set headers after they are sent. I'm arriving at this conclusion as I tried shooting two sequential requests instead of parallel ones and my code works just fine in this scenario.
You have a context problem with your callback!!!!
You should specify response & next for the session... Did you try to declare it with a var, it may solve your problem I think...
var callback=.....
In other case you need to pass both response() & next() to it...