ReferenceError:未为MERN应用定义validateResult

时间:2019-06-10 21:59:50

标签: javascript node.js mongodb express mern

我正在开发一个MERN应用,并尝试调用express-validator,但是由于某种原因,我收到了参考错误。

真的很感谢您的帮助!

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

// @route   POST api/users
// @desc    Register user
// @access  Public
router.post(
  '/',
  [
    check('name', 'Name is required')
      .not()
      .isEmpty(),
    check('email', 'Please include a valid email').isEmail(),
    check(
      'password',
      'Please enter a password with 6 or more charcters'
    ).isLength({ min: 6 })
  ],
  (req, res) => {
    /* req.body is body of data that will be sent to the route, must init middleware in server.js */
    const errors = validateResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    res.send('User route');
  }
);

module.exports = router;

这是错误消息:

ReferenceError: validateResult is not defined
    at router.post (C:\Users\Kelvin Yu\Documents\Day Zero\devconnector\routes\api\users.js:22:20)
    at Layer.handle [as handle_request] (C:\Users\Kelvin Yu\Documents\Day Zero\devconnector\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Kelvin Yu\Documents\Day Zero\devconnector\node_modules\express\lib\router\route.js:137:13)
    at runner.then.errors (C:\Users\Kelvin Yu\Documents\Day Zero\devconnector\node_modules\express-validator\check\check.js:16:7)
    at process._tickCallback (internal/process/next_tick.js:68:7)

1 个答案:

答案 0 :(得分:0)

此行

const errors = validateResult(req);

应该是

const errors = validationResult(req);

导入express-validate时,不是导入名为validateResult的函数,而是导入名为validationResult的函数:

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