一尘不染

Express验证器错误:expressValidator不是函数

node.js

我正在尝试安装和使用express-validator软件包。我已经安装了软件包版本(6.0.0),然后在server.js文件中,代码是:

const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
const express = require('express')
const nunjucks = require('nunjucks')
const sessionInMemory = require('express-session')
const cookieParser = require('cookie-parser')

然后往下几行,我输入了以下内容:

const app = express()
const documentationApp = express()
app.use(expressValidator())

当服务器重新加载更改(使用nodemon)时,应用程序崩溃并显示:

TypeError:expressValidator不是函数

我的server.js文件中还有其他代码段,但是我去除了大部分与我无关的代码。

expressValidator的控制台日志:

{ oneOf: [Function: oneOf],
  buildSanitizeFunction: [Function: buildSanitizeFunction],
  sanitize: [Function],
  sanitizeBody: [Function],
  sanitizeCookie: [Function],
  sanitizeParam: [Function],
  sanitizeQuery: [Function],
  buildCheckFunction: [Function: buildCheckFunction],
  check: [Function],
  body: [Function],
  cookie: [Function],
  header: [Function],
  param: [Function],
  query: [Function],
  checkSchema: [Function: checkSchema],
  matchedData: [Function: matchedData],
  validationResult: { [Function] withDefaults: [Function: withDefaults] },
  Result: [Function: Result] }

route.js文件的代码:

router.get('/email-adress', function (req, res) {
  res.render('email-adress', { success: req.session.success, errors: req.session.errors })
  req.session.errors = null
})

router.post('/finished', function (req, res) {
  let email = req.body.email

  req.checkBody('email', 'Email required').isEmail()

  var errors = req.validationErrors()
  if (errors) {
    req.session.errors = errors
    req.session.success = false
    res.redirect('/email-adress')
  } else {
    req.session.success = true
    res.redirect('/finished')
  }
})

阅读 356

收藏
2020-07-07

共1个答案

一尘不染

//just pass the checking as middleware not in the callback
//see here I've just passed an array for checking as middleware
// as the middleware is an array therefore you can add multiple checks in the array
router.post("/", [check('email', "your custom error message").isEmail()], (req, res) => {

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
   res.render('errorPage', { errors: errors.array() });
   //if api caller return res.status(422).json({ errors: errors.array() });
  }
  else{
    //here everything is ok to proceed
   res.render('successPage', { data });
   //to api caller  res.json({msg : "ok"})
  }

})
2020-07-07