【问题标题】:TypeError : next() is not a functionTypeError : next() 不是函数
【发布时间】:2021-11-12 01:37:23
【问题描述】:

我正在编写一个中间件函数来查找验证错误,如果发现错误,则给出某个输出,否则继续程序流程。我有两个具有确切代码的函数,但它们检查不同的模式。

我的第一个函数运行没有任何异常。但是,当我尝试执行第二个函数时,控制台中出现错误。

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.js express mongoose error-handling


    【解决方案1】:

    问题不在于 next() 中间件,而在于路由,因为我正在使用 validateReview 函数包装路由。

    我正在做这样的事情:

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

    然而,我应该做这样的事情:

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

    【讨论】:

      【解决方案2】:

      你好,如果你想使用中间件

      exports.middileware = (req,res,next)=>{
      
              try{
      
                  //middileware logic
      
              next();
      
              }catch(err){
      
                  //print the error
              })
              }
              
      }
      

      并在需要文件中调用导出的中间件文件检查中间件功能

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

      并像这样使用

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

      试试这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 2020-05-28
        • 2016-12-28
        • 2021-11-17
        • 2019-04-22
        • 2021-07-20
        • 1970-01-01
        相关资源
        最近更新 更多