Node.js Express报错ReferenceError: next未定义——Joi表单验证中间件问题
问题分析
报错的核心原因是中间件调用方式错误。validateCampground是标准的Express中间件(接收req, res, next三个参数),但你把catchAsync包裹的处理函数当作参数传给了它,导致validateCampground内部的next未被正确传入,从而触发ReferenceError。
解决方案
将validateCampground和catchAsync处理函数作为两个独立的中间件依次传给app.post,而非嵌套调用:
app.post( "/campgrounds", validateCampground, // 先执行验证中间件 catchAsync(async (req, res, next) => { const campground = new Campground(req.body.campground); await campground.save(); res.redirect(`/campgrounds/${campground._id}`); }) );
Express会按顺序执行中间件:先运行validateCampground完成校验,验证通过后调用next(),自动进入后续的catchAsync处理函数,此时next参数能被正确识别。
原写法错误原因
你之前的validateCampground(catchAsync(...))写法,是把catchAsync的返回值当作参数传给validateCampground,但validateCampground的定义是接收req,res,next,并非接收另一个函数。这种调用方式完全不符合Express中间件的使用规则,因此导致内部next未定义。
内容的提问来源于stack exchange,提问作者Umutcan Adıgüzel
相关产品推荐
相关产品推荐

