Home > database >  nodejs express ReferenceError: next is not defined
nodejs express ReferenceError: next is not defined

Time:12-04

I am trying to control the input I took from a form with joi validation. The function validateCampgrount is a middleware to check it but when I try to write the next function it says next is not defined.*

Where I am using next()

const validateCampground = (req, res, next) => {
  const { error } = campgroundSchema.validate(req.body);
  if (error) {
    const msg = error.details.map((el) => el.message).join(",");
    throw new ExpressError(msg, 400);
  } else {
    next();
  }
};

Error Message

next();
    ^

ReferenceError: next is not defined

Where I am using function

app.post(
  "/campgrounds",
  validateCampground(
    catchAsync(async (req, res, next) => {
      // if(!req.body.campground) throw new ExpressError('Invalid Data', 400)
      const campground = new Campground(req.body.campground);
      await campground.save();
      res.redirect(`/campgrounds/${campground._id}`);
    })
  )
);

CodePudding user response:

It seems that you are using middleware wrong. See this tutorial for a full guide.

In your code, you are wrapping a function in your middleware. Instead, you need to pass the middleware as a parameter to app.post(). Like this:

app.post("/campgrounds", validateCampground, async (req, res, next) => {
  const campground = new Campground(req.body.campground);
  await campground.save();
  res.redirect(`/campgrounds/${campground._id}`);
});

CodePudding user response:

The error message "next is not defined" indicates that the next() function is not available in the current scope.

In your code, you are calling the validateCampground() function and passing the result of this function (which is a middleware function that takes three arguments: req, res, and next) to the catchAsync() function. However, the catchAsync() function expects a callback function as its argument, not the result of calling a function.

To fix this error, you need to pass the callback function directly to the catchAsync() function, without calling ``validateCampground() first. Here is an updated version of the code that should fix the error:

app.post(
  "/campgrounds",
  catchAsync(async (req, res, next) => {
    validateCampground(req, res, next);

    // if(!req.body.campground) throw new ExpressError('Invalid Data', 400)
    const campground = new Campground(req.body.campground);
    await campground.save();
    res.redirect(`/campgrounds/${campground._id}`);
  })
);

In this updated code, the validateCampground() function is called within the callback function passed to the catchAsync() function, so the next() function is available in the correct scope. This should fix the "next is not defined" error.

  • Related