How can I solve TypeError: express-validator is not a function
How can I solve TypeError: express-validator is not a function
我正在使用 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 foo@bar.com"),
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);
}
在版本 6 中你不需要使用 app.use(expressValidator());只需使用中间件中的 express-validator 实用程序,here 您可以在 github 问题中看到一些实现:
Here's my implementation.
Remove:
app.use(expressValidator())
Then:
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.' });
}
});
我正在使用 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 foo@bar.com"),
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);
}
在版本 6 中你不需要使用 app.use(expressValidator());只需使用中间件中的 express-validator 实用程序,here 您可以在 github 问题中看到一些实现:
Here's my implementation. Remove:
app.use(expressValidator())
Then:
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.' });
}
});