express-validator - req.checkBody不是一个函数

时间:2018-05-15 20:39:06

标签: javascript node.js express npm express-validator

我现在已经尝试解决这个问题2个小时了,我有点沮丧。基本上,我想验证表单输入,但我总是得到这个错误。

TypeError: req.checkBody is not a function
at C:\Users\bobbo\Desktop\Develops\Project_folder\routes\index.js:19:7
at Layer.handle [as handle_request] (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:47:12)

我能找到的唯一信息就是告诉我写app.use(expressValidator());app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));之后,但是我做的并不重要,我仍然会遇到同样的错误。这是我使用的代码。

//index.js    
    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    var expressValidator = require('express-validator');

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(expressValidator());
    var router = express.Router();
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });

    router.get('/signup', function(req, res, next) {
      res.render('signup', { title: 'Express' });
    });

    router.post('/signup', function(req, res){
      var name = req.body.name;
      console.log(name);    //works
      req.checkBody("name", "Invalid name").notEmpty();
      var errors = req.validationErrors();
      if(errors){
        console.log('errors');
      } else{
        console.log('no errors');
      }
    });
    module.exports = router;

app.js

//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

的package.json

    //package.json
{
  "name": "pizzaonline",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "express-session": "^1.15.6",
    "express-validator": "^5.2.0",
    "http-errors": "~1.6.2",
    "morgan": "~1.9.0",
    "pug": "2.0.0-beta11"
  }

}

如果我注释掉req.checkBody("name", "Invalid name").notEmpty();,则要执行的下一个快速验证代码是var errors = req.validationErrors();,这给我一个相同的错误,告诉我req.validationErrors()不是函数。我是新手,但这告诉我快速验证器没有正确安装,我错了吗?任何帮助深表感谢。提前谢谢。

2 个答案:

答案 0 :(得分:2)

在您的嵌套路由文件(index.jsusers.js)中您正在创建新的应用实例并将该验证器附加到它实际上是不正确的。

创建新应用实例的原因您创建的新应用上下文与app中的app.js不同。

所以这是修复:

1)在app.js文件中的这一行上面附加快速验证器:

app.use(expressValidator());


app.use('/', indexRouter);
app.use('/users', usersRouter);

2)从嵌套路径文件中删除app对象生成,并使其看起来像:

//index.js    
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/signup', function(req, res, next) {
  res.render('signup', { title: 'Express' });
});

router.post('/signup', function(req, res){
  var name = req.body.name;

  req.checkBody("name", "Invalid name").notEmpty();
  var errors = req.validationErrors();
  if(errors){
    console.log('errors');
  } else{
    console.log('no errors');
  }
});

module.exports = router;

答案 1 :(得分:-1)

npm i --save express-validator@4

reqiure app.js

app.use(expressValidator());

然后重试

npm start