首页 > 解决方案 > TypeError : 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();
  }
};

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

只有在 validateReview 函数内部,下一个中间件函数才不会被识别为有效函数。

控制台错误日志

标签: node.jsexpressmongooseerror-handling

解决方案


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


推荐阅读