Src
Src

Reputation: 5482

NODEJS - Can't set headers after they are sent

I have function, that executes when 'dataCompiled' event fires, it looks like his:

eventEmitter.on('dataCompiled', function () {
        json = JSON.stringify({
          conversations: convs
        });
        res.json(json).end();
        return;
      });

But when i refreshing page, i getting error

Error: Can't set headers after they are sent.

Upvotes: 0

Views: 51

Answers (3)

Niels Heisterkamp
Niels Heisterkamp

Reputation: 735

Are you sure you're not sending more data after this call? You shouldn't have to use res.end(): http://expressjs.com/en/4x/api.html#res.end .

If there is another place in your code you're sending more data to res it will give the error message you are receiving, res.end is not fixing the underlying problem.

Upvotes: 0

Src
Src

Reputation: 5482

Finally figured out, need send json directly to end function, so it'll look like that:

res.end(json);

Upvotes: 1

Niels Heisterkamp
Niels Heisterkamp

Reputation: 735

You don't need to stringify and end a call to res.json if I'm not mistaken:

eventEmitter.on('dataCompiled', function () {
    return res.json({
        conversations: convs
    });
});

Upvotes: 0

Related Questions