Home > Back-end >  TypeError : next() is not a function
TypeError : next() is not a function

Time:09-17

I am writing a middleware function that looks for validation errors and if the error is found gives out a certain output else continues the program flow. I have two functions with the exact code but they check for different schemas.

My first function runs without any exception. However, when I try to execute the second function I get an error in the console.

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();
  }
};

const validateReview = (req, res, next) => {
  const { error } = reviewSchema.validate(req.body);
  if (error) {
    const msg = error.details.map((el) => el.message).join(",");
    throw new ExpressError(msg, 400);
  } else {
    next(); //this is the point where the exception occurs
  }
};

It is only inside the validateReview function where next middleware function is not recognised as a valid function.

Console Error Log

CodePudding user response:

The problem was not with the next() middleware but instead it was with the route as I was wrapping the route with the validateReview function.

I was doing something like this :

app.post(
  "/campgrounds/:id/reviews",
  validateReview(
  catchAsync(async (req, res) => {
    //my Logic here
  })
));

Whereas , I should have been doing something like this :

app.post(
  "/campgrounds/:id/reviews",
  validateReview,
  catchAsync(async (req, res) => {
    //my logic here
  })
);

CodePudding user response:

hi if you want to use a middileware

exports.middileware = (req,res,next)=>{

        try{

            //middileware logic

        next();

        }catch(err){

            //print the error
        })
        }
        
}

and call the exported middileware file in requires file to check the middileware function

const { middileware } = require('path');

and use like this

router.get('/routename',middleware,nextfunction)  //router you can choose as you like get,post,patch anything

try this out

  • Related