如何在nodeJs中使用express-validator?

时间:2018-11-15 04:22:40

标签: node.js express express-validator

我正在我的nodeJs示例中尝试使用express-validator,
我尝试对用户名和密码是否有效进行基本验证,
用户名必须是电子邮件地址,并且
密码长度必须至少为5个字符。
我正在使用official doc

中的示例

以下是我尝试运行的示例代码-

const express = require('express');
const app = express();
const { check, validationResult } = require('express-validator/check');

app.use(express.json());

app.all('/*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', "GET, POST, PUT, PATCH, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", 'Content-Type, Accept, X-Access-Token');

  if (req.method == 'OPTIONS') {
      res.status(200).end();
  } else {
      next();
  }
});

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));

});

var server = app.listen(8085, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
});

以下是我使用POSTMAN调用API时遇到的错误-
enter image description here

由于某些原因,尽管传递了有效的电子邮件作为用户名和5个字符长的密码,但验证仍然失败,
这是什么错误,有人可以帮忙吗?

0 个答案:

没有答案