Search code examples
javascriptnode.jsexpressnpmexpress-validator

express-validator - req.checkBody is not a function


I've been trying to fix this for 2 hours now and I'm getting a little frustrated. Basicly, I want to validate a form input, but I always get this error.

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)

Pretty much the only info I could find is telling me to write the app.use(expressValidator()); after app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));, but it doesn't matter what I do, I still get the same error. Here is the code I use.

//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"
  }

}

If I comment out req.checkBody("name", "Invalid name").notEmpty();, the next express-validation code to be executed is var errors = req.validationErrors();, giving me an identical error telling me req.validationErrors() is not a function. I'm new to this but this tells me that express-validator is not properly installed, am I wrong? Any help is much appreciated. Thanks in advance.


Solution

  • In Your nested route files (index.js and users.js) You're creating new app instance and attaching that validator to it that in fact is not correct.

    Cause by creating new app instance You create new app context that is different from app in app.js.

    So here's the fix:

    1) attach express validator above this lines in app.js file:

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

    2) remove app object generation from nested route files and make it look like:

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