You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express Node.js配合Passport创建用户时报req.checkBody is not a function错误

问题分析与修复方案

报错触发原因

  • 核心原因是你安装的express-validator为v6及以上的新版本,该版本已经完全移除了旧版提供的req.checkBody、req.validationErrors等请求对象挂载API,也不再支持直接将expressValidator作为全局中间件注册的用法,旧API调用自然会报错。
  • 除此之外你当前的app.js仅引入了expressValidator依赖,没有按旧版本的要求完成中间件挂载,即使安装的是旧版也无法正常使用相关API。

修复方案

方案一:降级到兼容旧API的版本(无需修改业务代码,成本最低)

  1. 先卸载当前版本,安装支持旧API的5.x版本:
npm uninstall express-validator
npm install --save express-validator@5.3.1
  1. 在app.js中注册express-validator中间件,注意要放在body-parser中间件的后面:
// 原有body-parser注册代码
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
// 新增这一行注册校验中间件
app.use(expressValidator());

完成后原有控制器代码无需修改即可正常运行。

方案二:适配新版本API(推荐,长期维护更友好)

  1. 移除app.js中const expressValidator = require('express-validator');这行引入代码,新版本不需要全局引入注册。
  2. 修改注册接口的路由定义,新增校验规则:
// 从express-validator引入需要的方法
const { body, validationResult } = require('express-validator');

// 你的注册POST路由修改为如下结构,把校验规则加到路由参数中
app.post('/create-user',
  body('username', 'UserName is required').notEmpty(),
  body('password', 'Password is required').notEmpty(),
  body('password2', '两次输入的密码不一致').equals('password'),
  usersController.createUserForm
);
  1. 修改控制器中的校验逻辑,替换原有req.checkBody相关代码,同时修复原有代码的变量作用域、跳转方法笔误问题:
exports.createUserForm = (req, res, next) => {
  console.log('Post CREATE CATEGORY /create-user');
  const username = req.body.username;
  const password = req.body.password;
  const password2 = req.body.password2;

  // 替换原有checkBody和validationErrors的代码
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.render('./register', {
      errors: errors.array()
    });
    return;
  } 

  // 修复原有newUser定义在else块内、后续逻辑无法访问的问题
  let newUser = new userSchema({
    username: username,
    password: password
  });

  // 后续bcrypt加密和保存用户的逻辑,修复原有req.redirect的笔误
  bycrypt.genSalt(10, function(err, salt) {
    bycrypt.hash(newUser.password, salt, function(err, hash) {
      if (err) {
        console.log(err);
        return;
      }
      newUser.password = hash;
      newUser.save(function(err) {
        if (err) {
          console.log(err);
          return;
        } else {
          req.flash('success', 'You successfully registered')
          res.redirect('/halalMunchies/login');
        }
      })
    })
  })
}

内容的提问来源于stack exchange,提问作者Hesham Eldawy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:15:03