Alexander Mills
Alexander Mills

Reputation: 100290

Express - preventing two+ responses from being sent

Using Node.js Express server, we get errors "can't sent headers twice.." if we attempt to send two responses to the same request. I want to figure out the best way to prevent two responses from being sent, for this particular case, but potentially for others as well.

I have a simple /test route that returns information about the state of the server, it looks like this:

app.get('/test', function (req, res, next) {

    var client = redis.createClient();

    var response = {};

    var alreadySentResponse = false; //I use a boolean to check if I already sent a response

    client.on("error", function (err) {   //this callback will invoke res.send
        log.error('error in redis client test error callback:', err);
        if(alreadySentResponse === false){
            alreadySentResponse = true;
            res.status(500).send({"test message from SmartConnect": err});
        }

    });

    client.info(function (err, resp) { //this callback will also invoke res.send
        response['redisInfo'] = resp;
        if(alreadySentResponse ===false){
            alreadySentResponse = true;
            res.status(200).send({"test message from SmartConnect": response});
        }
    });
});

is there a better way to do this? Can the res object keep track of whether it has been sent already? It seems to crash the server if res.send gets invoked twice, etc. The other problem of course, is that if there is an internal error with the client, if the success response gets sent, that doesn't mean I don't want to also send the client.on('error') message on top of that...

Upvotes: 1

Views: 2480

Answers (1)

laggingreflex
laggingreflex

Reputation: 34677

You can check for res.headersSent

if (res.headersSent) return;
client.info(function (err, resp) { //this callback will also invoke res.send
    if (res.headersSent) return;
    response['redisInfo'] = resp;
    res.status(200).send({"test message from SmartConnect": response});
});

Upvotes: 5

Related Questions