【问题标题】:Express Validator Error: expressValidator is not a functionExpress Validator 错误:expressValidator 不是函数
【发布时间】:2019-11-06 02:34:40
【问题描述】:

我正在尝试安装和使用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] }

routes.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')
  }
})

【问题讨论】:

  • 控制台记录你的 expressValidator 并显示结果
  • 检查文档express-validator.github.io/docs/6.0.0 它与您在这里所做的不同,它需要 const { check, validationResult } = require('express-validator');然后在路由中将检查作为中间件传递 [ check('username').isEmail(), check('password').isLength({ min: 5 }) ]
  • expressValidator 是一个对象而不是一个函数。 ;)
  • @ArpitPandey 我可以看到那里的区别,我刚刚添加了 routes.js 文件的代码,它检查电子邮件输入以确保它是有效的电子邮件地址。我不确定如何为版本 6 重写该代码?

标签: javascript node.js express


【解决方案1】:

Express Validator 已更新,因此您不能以这种方式使用它 This is a new way 使用 express 验证器

天气棒使用以前的版本或使用它的当前语法。

npm uninstall express-validator
npm install express-validator@5.3.0

【讨论】:

    【解决方案2】:
    //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"})
      }
    
    })
    

    【讨论】:

    • 这非常有效,谢谢。最后一个问题,现在它正在返回 JSON,如果有错误,我将如何将 JSON 放入模板并呈现电子邮件地址页面,或者如果它很好,然后呈现完成的页面?感谢您的帮助
    • 如果您的视图在 API 中,您可以只在 if else 条件中使用 res.render,或者如果您的视图是单独的,则只需将 JSON 返回给 API 调用者,然后决定要显示的内容.
    • 检查我是否进行了更改
    • 搞定了,最后的问题是它显示 errorPage 但带有成功的 URL(完成页面)。我猜它需要一些逻辑 if errors.isEmpty go/stay on the original page而不是转到帖子页面?
    • 然后只需使用 express 的 red.redirect 功能,它将根据您的需要重定向到 successUrl 或 errorUrl,只需查看此线程 stackoverflow.com/questions/19035373/…
    【解决方案3】:

    是的!即使我有同样的问题。您可以通过在根文件夹中编写命令来更改版本。

    命令:

    npm install express-validator@5.3.1 --save-exact
    

    【讨论】:

      【解决方案4】:
      const { check, validationResult } = require('express-validator');
      router.post('/finished', function (req, res) {
      let email = req.body.email
      
      check('email', 'Email required').isEmail()
      
      var errors = validationResult(req)
      if (errors) {
        req.session.errors = errors
        req.session.success = false
        res.redirect('/email-adress')
        } else {
        req.session.success = true
        res.redirect('/finished')
        }
      })
      

      这样做。并删除

      app.use(expressValidator()) 
      

      行。

      【讨论】:

      • 它不会崩溃,但在提交时会转到 /finished 但错误为req.check is not a function
      【解决方案5】:
      just update the express validator , will do the tri
      

      npm install express-validator@5.3.1 --save-exact

      【讨论】:

        【解决方案6】:

        转到 package.json 将“express-validator”:“^6.6.0”更改为“express-validator”:“^5.3.0”,然后手动运行 npm i

        【讨论】:

        • 问题是使用 6.0.0 版本的库。理解答案以解释为什么要降级库的版本以及为什么要手动执行它可能会很有用。可以在与答案相同的库版本中解决吗?
        • 我想知道你是否甚至在给出负面评价之前运行解决方案......这很容易解决问题,就像上面的其他帖子一样最好停止寻找毫无意义的借口来给予负面评价。
        【解决方案7】:

        这发生在我身上,因为我正在学习一个过时的(2019 年)教程。如果您安装旧版本(5.3.1 对我有用),它可以工作。我与 Jonathan Wexler 所著的“Get Programming with Node.js”一书一起遇到了这个问题。

        【讨论】:

          【解决方案8】:
          app.use(expressValidator());
          

          将此行替换为

          app.use(expressValidator);
          

          【讨论】:

          • 谢谢,但这引发了一个新错误:throw new TypeError('app.use() requires a middleware function')
          猜你喜欢
          • 2020-02-09
          • 1970-01-01
          • 1970-01-01
          • 2022-08-05
          • 2018-07-23
          • 1970-01-01
          • 1970-01-01
          • 2018-08-22
          • 2016-11-07
          相关资源
          最近更新 更多