收到错误:req.validatonErrors不是函数,但我不确定为什么

时间:2020-05-19 01:49:45

标签: javascript node.js mongodb express

我是新手,正在学习有关node / express / mongo的Udemy课程,但是遇到了我无法解决的障碍。我在表单代码中使用express-validator,无法克服此错误。我怀疑我使用Express-validator的方式存在一些错误。

在users.js中

var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest: './uploads'});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// Register Page
router.get('/register', function(req, res, next) {
  res.render('register', { title: 'Register Page'})
});
// Login Page
router.get('/login', function(req, res, next) {
  res.render('login', { title: 'Login Page'})
});

router.post('/register', upload.single('profileimage'), function(req, res, next) {
  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;

  if(req.file){
    console.log('Uploading Picture file...')
    var profileimage = req.file.filename;
  } else {
    console.log('No file uploaded');
    var profileimage = 'noimage.jpg';
  }
  // Form Validator
  req.checkBody('name', 'Name field is required').notEmpty();
  req.checkBody('email', 'Email field is required').notEmpty();
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('username', 'Username field is required').notEmpty();
  req.checkBody('password', 'Password field is required').notEmpty();
  req.checkBody('password2', 'Passwords do not match.').equals(req.body.password);

  // Check Errors
  app.use(expressValidator({
    errorFormatter: function(param, msg, value) {
        var namespace = param.split('.')
        , root    = namespace.shift()
        , formParam = root;

      while(namespace.length) {
        formParam += '[' + namespace.shift() + ']';
      }
      return {
        param : formParam,
        msg   : msg,
        value : value
      };
    }
  }));
  if(errors){
    res.render('register', {
    errors: errors
  });
  } else {
  console.log('No Errors')
  }
});

module.exports = router;

在app.js中

var express = require('express');
var path = require('path');
//var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var expressValidator = require('express-validator');
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
//var bcrypt = require('bcryptjs');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
  secret:'secret',
  saveUninitialized: true,
  resave: true
}));

// Passport
app.use(passport.initialize());
app.use(passport.session());

// Validator
app.use(expressValidator())

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

在register.pug

extends layout

block content
  h2.page-header Register
  p Please register using the form below
  form(action="/users/register", method="post", enctype='multipart/form-data')
    .form-group
    label Name
    input.form-control(name='name', type='text', placeholder='Enter Name')
    .form-group
    label Email
    input.form-control(name='email', type='text', placeholder='Email')
    .form-group
    label Username
    input.form-control(name='username', type='text', placeholder='Username')
    .form-group
    label Password
    input.form-control(name='password', type='password', placeholder='Password')
    .form-group
    label Confirm Password
    input.form-control(name='password2', type='password', placeholder=' Confirm Password')
    .form-group
    label Profile Image
    input.form-control(name='profileimage', type='file')
    input.btn.btn-primary(type='submit', name='submit', value='Submit')

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为表达验证者更改了他们的文档和github页面,您不必使用更长的中间件。 https://express-validator.github.io/docs/5.3.0/index.html

// Check Errors
  app.use(expressValidator({
    errorFormatter: function(param, msg, value) {
        var namespace = param.split('.')
        , root    = namespace.shift()
        , formParam = root;

      while(namespace.length) {
        formParam += '[' + namespace.shift() + ']';
      }
      return {
        param : formParam,
        msg   : msg,
        value : value
      };
    }
  })); 

我不确定是否是这样。尝试

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

实际上我不是专业人士,但我只是想帮助您。如果是错的话,我们将进行研究,直到取得成功。