somesh
somesh

Reputation: 73

why the underlying code gets executed in a block even after invoking next() in express?

exports.getTour = catchAsync(async (req, res, next) => {
  const tour = await Tour.findById(req.params.id);

  if (!tour) {
    next(new AppError('No tour found with that ID', 404));
  }

  res.status(200).json({
    status: 'success',
    data: {
      tour
    }
  });
});

if tour variable is empty I am invoking the next() method and creating an error inside it using a class constructor but even after invoking the next() the response was sent as a response to the request, and then i am getting '[ERR_HTTP_HEADERS_SENT]:' error. Why the block is not exiting even after next is called?

Upvotes: 1

Views: 67

Answers (3)

Ahmed Taha Ezzine
Ahmed Taha Ezzine

Reputation: 1

in a middleware, you should execute the next() function, try

module.exports.getTour = async (req, res, next) => {
  const tour = await Tour.findById(req.params.id);
  if (!tour) res.send("No tour found with that ID");

  req.tour = tour;

  next();
};

Upvotes: -1

jacobkim
jacobkim

Reputation: 1100

next() makes a current call back function pass to the next request which has the same URL. Requests couldn't be finished if the response is not activated in the call back function. To finish a call back function, a response should be written with any function. To use next() at the call back there should be another request like,

// request to be passed by `next()`
app.request('same URL', (res, req) => {

...

res.end()

});

This is an example on express document about next().

If you want to finish with sending an error then just respond with JSON res.status(404).send("error": "No tour found with that ID").

Upvotes: 1

fortunee
fortunee

Reputation: 4352

Because you need to return in order to breakout of the function if tour is empty.

So do this

if (!tour) {
  return next(new AppError('No tour found with that ID', 404));  
}

Upvotes: 2

Related Questions