Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: req.checkBody is not a function

I'm trying to implement some validation in a sign up system, but I get the error:

     TypeError: req.checkBody is not a function

from the following code:

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

  });

I've checked and it's getting the info from the front end, and I've had almost the same code work in another app (where is wasn't wrapped in module.exports = function(app, express) { }

like image 262
crash springfield Avatar asked Aug 26 '16 20:08

crash springfield


3 Answers

You need to install express-validator using below command

npm install express-validator

then add

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

immediately after

var api = express.Router();

See TypeError: req.checkBody is not a function including bodyparser and expressvalidator module for more details

like image 199
Abhishek Parikh Avatar answered Nov 11 '22 18:11

Abhishek Parikh


I encountered the same problem, I found out that the problem was from the current version of express_validator. I had to degrade to "express-validator": "5.3.1", and it worked for me. I think the need to fix the issue.

like image 21
Amadi Chukwuemeka Austin Avatar answered Nov 11 '22 18:11

Amadi Chukwuemeka Austin


With express-validator 6 you will have to do the following:

import

var router = express.Router();
var { body, validationResult} = require('express-validator');

validation

body('username').isEmail()
body('password').isLength({ min: 5 })

errors

const errors = validationResult(req);
like image 3
Sandip Subedi Avatar answered Nov 11 '22 18:11

Sandip Subedi