【问题标题】:app.use(validator()) TypeError: validator is not a functionapp.use(validator()) TypeError: 验证器不是函数
【发布时间】:2019-07-05 18:13:11
【问题描述】:

大家好,我正试图在我的应用程序中安装 express-validator,但是当我试图要求模块并在 app.use() 函数中使用它时,我遇到了TypeError: validator is not a function

app.js代码

var validator = require("express-validator");

---

app.use(express.json());
app.use(express.urlencoded({ extended: false }));      app.use(cookieParser());
app.use(validator());

【问题讨论】:

  • 您尝试使用哪个版本的 express-validator?答案可能取决于此,因为不同版本的初始化可能不同

标签: node.js express


【解决方案1】:

require("express-validator") 不是中间件。中间件是:

check([field, message])

body([fields, message])

oneOf(validationChains[, message]) ..etc..

取自doc的基本示例:

// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator');

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 2017-09-29
    相关资源
    最近更新 更多