2

After calling res.send(), is there a need to call a return or somehow exit the callback function in order to make sure no further code executes? Like how when calling a header function in PHP, you need to call exit after that to prevent further code from being executed.

app.post('/create', function(req, res) {
  if(req.headers['x-api-key'] === undefined) {
     res.send({msg: "Goodbye"});
  }
  // other code that should only be processed if it has that header.

});
Ryan
  • 14,053
  • 8
  • 59
  • 102

3 Answers3

9

Just use return:

app.post('/create', function(req, res) {
  if(req.headers['x-api-key'] === undefined)
    return res.send({msg: "Goodbye"});

  // other code that should only be processed if it has that header.

});
mscdex
  • 99,783
  • 13
  • 184
  • 147
0

As per the node manual:

The method, response.end(), MUST be called on each response.

PeterVC
  • 4,554
  • 2
  • 15
  • 14
-1

Use always next().

app.post('/create', function(req, res, next) {
     if(req.headers['x-api-key'] === undefined) {
        req.send({msg: "Goodbye"});
        return next();

      }
      // other code that should only be processed if it has that header.

   });
Nitish Kumar
  • 4,840
  • 2
  • 19
  • 38