node.js - Express - preventing two+ responses from being sent -


using node.js express server, errors "can't sent headers twice.." if attempt send 2 responses same request. want figure out best way prevent 2 responses being sent, particular case, potentially others well.

i have simple /test route returns information state of server, looks this:

app.get('/test', function (req, res, next) {      var client = redis.createclient();      var response = {};      var alreadysentresponse = false; //i use boolean check if sent response      client.on("error", function (err) {   //this callback invoke res.send         log.error('error in redis client test error callback:', err);         if(alreadysentresponse === false){             alreadysentresponse = true;             res.status(500).send({"test message smartconnect": err});         }      });      client.info(function (err, resp) { //this callback invoke res.send         response['redisinfo'] = resp;         if(alreadysentresponse ===false){             alreadysentresponse = true;             res.status(200).send({"test message smartconnect": response});         }     }); }); 

is there better way this? can res object keep track of whether has been sent already? seems crash server if res.send gets invoked twice, etc. other problem of course, if there internal error client, if success response gets sent, doesn't mean don't want send client.on('error') message on top of that...

you can check res.headerssent

if (res.headerssent) return; 
client.info(function (err, resp) { //this callback invoke res.send     if (res.headerssent) return;     response['redisinfo'] = resp;     res.status(200).send({"test message smartconnect": response}); }); 

Comments

Popular posts from this blog

symfony - TEST environment only: The database schema is not in sync with the current mapping file -

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -