我该如何解决TypeError:express-validator不是函数

问题描述 投票:0回答:1

我正在使用Express-validator版本6.4.0。运行服务器时出现此错误。我尝试使用自定义验证,并为验证器,控制器和路由创建了单独的文件。

这是主服务器文件“ index.js”

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const {expressValidator} = require('express-validator');
const db = require('./models');

const app = express();

db.sequelize.sync({force: true}).then(() => { console.log("Connected to DB") }).catch((err) => {console.log(err)});

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());

app.use(expressValidator());

require('./routes/user.routes')(app);

我的验证程序文件具有两个功能,一个用于检查验证,另一个用于基于验证“ user.validator.js”返回响应。

const { check, validationResult } = require('express-validator');

const checkValidation = (method) => {
    switch (method) {
        case "create": {
            return [
                check("first_name").exists().withMessage("It is mandatory to enter your first name"),
                check("last_name").exists().withMessage("It is mandatory to enter your last name"),
                check("email").exists().withMessage("It is mandatory to enter email")
                .isEmail().withMessage("The email must be in correct format as [email protected]"),
                check("password").exists().withMessage("It is mandatory to enter password")
                .isLength({ min: 6 }).withMessage("Password must be at least 6 characters in length"),
                check("role").exists().withMessage("It is mandatory to enter role")
                .isInt().withMessage("Role must be a number")
            ];
        }
    }
}

const validate = (req, res, next) => {
    const errors = validationResult(req);

    if (errors.isEmpty()) {
        return next();
    }

    const extractedErrors = [];
    errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))

    return res.status(422).json({
        errors: extractedErrors,
    });
}

module.exports = {
    checkValidation,
    validate,
};

这是user.controller.js中我唯一的功能

exports.create = (req, res, next) => {
    try {
        console.log(req.body);
        return res.json(req.body);
    } catch (error) {
        return next(error);
    }
}

这是路由文件“ user.routes.js”

module.exports = app => {
    const user = require('../controllers/user.controller');
    const {checkValidation, validate } = require('../validators/user.validate');
    let router = require('express').Router();

    //route to create a new tutorial
    router.post('/', checkValidation('create'), validate(), user.create);

    app.use('/api/users', router);
}
javascript mysql node.js express mern
1个回答
0
投票

在版本6中,您无需使用app.use(expressValidator());只需在中间件中使用express-validator实用程序,here您可以在github问题中看到一些实现:

这是我的实现。删除:

app.use(expressValidator())

然后:

var router = express.Router();
const { check, validationResult } = require('express-validator');

router.post('/register',
  [
    check('email', 'Email is not valid').isEmail(),
    check('username', 'Username field is required').not().isEmpty(),
    check('password', 'Password field is required').not().isEmpty())
  ], 
  function(req, res, next) {

  // Check Errors
  const errors = validationResult(req);
  if (errors) {
    console.log(errors);
    res.render('register', { errors: errors.array() });
  }
  else {
    console.log('No Errors');
    res.render('dashboard', { message: 'Successful Registration.' });
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.