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

req.checkBody不是函数:express-validator中间件失效问题求助

Fixing req.checkBody is not a function Error in express-validator

Hey there! The error you're hitting happens because the old req.checkBody() method (and the entire request-based validation API) was removed starting in express-validator v4. The library shifted to a middleware-based approach instead. Let's get your code working again with the modern API:

Step 1: Ensure you have the latest express-validator

First, make sure you're using the current version (if you downgraded before, you can upgrade back):

npm install express-validator

Step 2: Update Your Route Code

Here's how to rewrite your registration route to use the new validation pattern. I'll highlight the key changes:

var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('passportapp', ['users']);
var bcrypt = require('bcryptjs');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// Add these imports from express-validator
const { check, validationResult } = require('express-validator');

// Login Page - GET
router.get('/login', function(req, res){
    res.render('login');
});

// Register Page - GET
router.get('/register', function(req, res){
    res.render('register');
});

// Register - POST (updated with new validation)
router.post('/register', 
  // Add validation middleware here
  [
    check('name', 'Name field is required').notEmpty(),
    check('email', 'Email field is required').notEmpty(),
    check('email', 'Please use a valid email address').isEmail(),
    check('username', 'Username field is required').notEmpty(),
    check('password', 'Password field is required').notEmpty(),
    check('password2', 'Passwords do not match').custom((value, { req }) => {
      return value === req.body.password;
    })
  ],
  function(req, res){
    // Get Form Values
    var name = req.body.name;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var password2 = req.body.password2;

    // Check for errors using validationResult
    const errors = validationResult(req);

    if(!errors.isEmpty()){
        console.log('Form has errors...');
        res.render('register', {
            errors: errors.array(), // Use .array() to get error objects
            name: name,
            email: email,
            username:username,
            password: password,
            password2: password2
        });
    } else {
        var newUser = {
            name: name,
            email: email,
            username:username,
            password: password
        }

        db.users.insert(newUser, function(err, doc){
            if(err){
                res.send(err);
            } else {
                console.log('User Added...');
                //Success Message
                req.flash('success', 'You are registered and can now log in');
                // Redirect after register
                res.location('/');
                res.redirect('/');
            }
        });
    }
});

module.exports = router;

Key Changes Explained:

  • We import check (replaces req.checkBody) and validationResult (replaces req.validationErrors()) directly from express-validator.
  • Validation rules are now passed as middleware to the router.post() method, instead of being called inside the route handler.
  • For the password match check, we use .custom() instead of .equals() because we need access to the request body to compare passwords.
  • To get the error list, we use errors.array() instead of just errors—this gives you the same structure as the old req.validationErrors() output.

Why This Works

The newer express-validator API is more flexible and aligns better with Express's middleware pattern. It separates validation logic from your route handler, making code cleaner and easier to maintain.

内容的提问来源于stack exchange,提问作者Keshavaa Shaiskandan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:57:45