一尘不染

TypeError:req.checkBody不是函数

node.js

我正在尝试在注册系统中实施一些验证,但出现错误:

     TypeError: req.checkBody is not a function

从以下代码中:

module.exports = function(app, express) {
  var express = require('express');
  var api = express.Router();

  // post users to database
  api.post('/signup', function(req, res) {
    var email = req.body.email;
    var password = req.body.password;
    var password2 = req.body.password2;
    var key = req.body.key;

    // Validation
    req.checkBody('email', 'Email is required.').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail(); 
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors) {
      res.render('register', {
        errors: errors
      });
    } else {
      var user = new User({
        email: email,
        password: password
      });
      var token = createToken(user);
    }

    // save to database
    user.save(function(err) {
      if (err) {
        res.send(err);
        return;
      }

      res.json({
        success: true,
        message: 'User has been created',
        token: token
      });
    });

  });

我已经检查过了,并且从前端获取了信息,并且我在另一个应用程序中也执行了几乎相同的代码(模块中没有包装代码。exports =
function(app,express){}


阅读 190

收藏
2020-07-07

共1个答案

一尘不染

您需要express-validator使用以下命令进行安装

npm install express-validator

然后加

var expressValidator = require('express-validator');
api.use(expressValidator())

之后立马

var api = express.Router();
2020-07-07