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,392
  • 8
  • 62
  • 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
  • 104,356
  • 15
  • 192
  • 153
0

As per the node manual:

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

PeterVC
  • 4,574
  • 2
  • 16
  • 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,850
  • 3
  • 20
  • 38