node.js - 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 函数内部,下一个中间件函数才不会被识别为有效函数。
解决方案
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
推荐阅读
- ruby - 为什么我在 Ruby 中进行简单的矩阵添加操作会出现“无方法”错误?我的其他程序中有许多基本相同的行
- angular - 从对象分配 mat-button-toggle-group 的默认值
- reactjs - react-bootstrap 手风琴 defaultActiveKey 未打开默认活动密钥
- typescript - 如何从.then中获取变量
- java - 通过给定索引获取数据
- flutter - 我可以让 ListView 中的项目超出容器限制吗?
- python - 一个奇怪的泡菜故障
- firebase - 什么时候一起使用 Firebase 实时数据库和 Firestore 才有意义?
- cocoa - Cocoapod:警告:URI.escape 已过时
- node.js - Nodejs 重复拒绝(未处理的一个并在 try/catch 块中)