Home > Blockchain >  I am getting an error while trying to create an user using Express NodeJs and Passport
I am getting an error while trying to create an user using Express NodeJs and Passport

Time:11-09

I am trying to create a user registration page, but when i tries to make a post request to save the user in the db, i get an error that error TypeError: req.checkBody is not a function Also i use this npm install --save express-validator

app.js the Main file

 const express = require('express');

const dotenv = require('dotenv');

const app = express(); //main app variable that represents the application

const morgan = require('morgan');

const bodyparser = require("body-parser"); //requiring the body parser         

const path = require('path');

const expressValidator = require('express-validator');

const bycrypt = require('bcryptjs');

the controller PostRequest call Back function

    exports.createUserForm = (req, res, next) => {

    //return to the list
    //res.redirect('/all-users');

    console.log('Post CREATE CATEGORY /create-user');

    // getting the request body

    const username = req.body.username;

    const password = req.body.password;

    const password2 = req.body.password2;


    // check the body request by using express validator

    req.checkBody('username', 'UserName is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'UserName is required').equals(req.body.password);

    // get the error if there are any 

    let errors = req.validationErrors();

    // check then 

    if (errors) {
        res.render('./register', {
            errors: errors
        });
    } else {
        let newUser = new userSchema({

            username: username, // first is the attribute NAME of the model , second is the name value tag in the html file
            password: password
        });
    }

    //hash the user's password before we save the user

    bycrypt.genSalt(10, function(err, salt) {

        bycrypt.hash(newUser.password, salt, function(err, hash) {
            if (err) {
                //ERROR PAGE
                console.log(err);
            }

            /// Hashing the password
            newUser.password = hash;

            /// saving the user

            newUser.save(function(err) {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    req.flash('success', 'You successfully registered')
                    req.redirect('/halalMunchies/login');
                }
            })
        })
    })




}

The Error in the log

TypeError: req.checkBody is not a function
at exports.createUserForm (E:\HalalMunchies\server\controller\usersController.js:36:9)
at Layer.handle [as handle_request] (E:\HalalMunchies\node_modules\express\lib\router\layer.js:95:5)
at next (E:\HalalMunchies\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\HalalMunchies\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\HalalMunchies\node_modules\express\lib\router\layer.js:95:5)
at E:\HalalMunchies\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\HalalMunchies\node_modules\express\lib\router\index.js:335:12)
at next (E:\HalalMunchies\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\HalalMunchies\node_modules\express\lib\router\index.js:174:3)
at router (E:\HalalMunchies\node_modules\express\lib\router\index.js:47:12)

CodePudding user response:

You need to add in app.js

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

CodePudding user response:

I don't see any configurations in your code.

check your express-validator configurations with the official documentation for this package

// ...rest of the initial code omitted for simplicity.
const { body, validationResult } = require('express-validator');

app.post(
  '/user',
  // username must be an email
  body('username').isEmail(),
  // password must be at least 5 chars long
  body('password').isLength({ min: 5 }),
  (req, res) => {
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    User.create({
      username: req.body.username,
      password: req.body.password,
    }).then(user => res.json(user));
  },
);
  • Related