0

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.

haltTm
  • 534
  • 1
  • 6
  • 25

1 Answers1

2

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...

  • Declaring callback with var helps. Could you please elaborate on why this works? What's the difference between a callback with and without var? I am a javascript beginner. – haltTm May 14 '13 at 10:31
  • Without var your fonction is "global" and honestly I'm not sure about what is is "closure" (i think all call to callback take last function but not sure) – Jean-Michel Trayaud May 14 '13 at 11:02
  • With var your create a local instance or your function for each getdata call, And your are sure about it's closure..... Hope it's more clear like this :) – Jean-Michel Trayaud May 14 '13 at 11:04