errors generated by express validator with node express

2.5k views Asked by At

I am using nodejs, express, & express-validator. I am trying to use express validator on my sign_up page . Express-validator generates the errors in an array of objects.
the error:
Result {
formatter: [Function: formatter],
errors: [
{
value: undefined,
msg: 'Please Enter a Valid Username',
param: 'username',
location: 'body'
},
{
value: undefined,
msg: 'Please enter a valid email',
param: 'email',
location: 'body'
},
{
value: undefined,
msg: 'Please enter a valid password',
param: 'password',
location: 'body'
}
]
}

I use postman to test the register operation and send the following in the request:
{ "username":"ruba", "email":"[email protected]", "password":"1234544545@"

}

my user.js code:

// Filename : user.js

const express = require("express");
const { check, validationResult} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const router = express.Router();

const User = require("../model/User");

/**
 * @method - POST
 * @param - /signup
 * @description - User SignUp
 */

router.post(
    "/signup",
    [
        check("username", "Please Enter a Valid Username")
        .not()
        .isEmpty(),
        check("email", "Please enter a valid email").isEmail(),
        check("password", "Please enter a valid password").isLength({
            min: 6
        })
    ],
    async (req, res) => {
   
        const errors = validationResult(req);
        console.log(errors);
        if (!errors.isEmpty()) {
            console.log("error sign");

            return res.status(400).json({
                errors: errors.array()
            });
            console.log("error sign2");

        }
        console.log("error sign3");

        const {
            username,
            email,
            password
        } = req.body;
        try {
            let user = await User.findOne({
                email
            });
            if (user) {
                return res.status(400).json({
                    msg: "User Already Exists"
                });
            }

            user = new User({
                username,
                email,
                password
            });

            const salt = await bcrypt.genSalt(10);
            user.password = await bcrypt.hash(password, salt);

            await user.save();

            const payload = {
                user: {
                    id: user.id
                }
            };

            jwt.sign(
                payload,
                "randomString", {
                    expiresIn: 10000
                },
                (err, token) => {
                    if (err) throw err;
                    res.status(200).json({
                        token
                    });
                }
            );
        } catch (err) {
            console.log(err.message);
            res.status(500).send("Error in Saving");
        }
    }
);


module.exports = router;

my index code:

const express = require("express");
const bodyParser = require("body-parser");
const user = require("./routes/user"); //new addition
const InitiateMongoServer = require("./config/db");

// Initiate Mongo Server
InitiateMongoServer();

const app = express();

// PORT
const PORT = process.env.PORT || 4000;

// Middleware
//app.use(bodyParser.json());
app.use(express.json());

app.get("/", (req, res) => {
  res.json({ message: "API Working" });
});


app.use("/user", user);

app.listen(PORT, (req, res) => {
  console.log(`Server Started at PORT ${PORT}`);
});

so please help me. what is the problem??

Edit: It's solved. the problem was in the postman settings (the contents type must be JSON)

1

There are 1 answers

8
drocha87 On BEST ANSWER

Did you enabled

app.use(express.json());

Because I cant see any kind of problem with you code (about the express-validator).

I suggest you after this fix, you to change check to body since you wants only to check the content of body.

I'm using an middleware to helps to me keep my code short and legible, and I'll share with you

function validation(validations: Array<ValidationChain>) {
    return async (req: Request, _res: Response, next: NextFunction) => {
        await Promise.all(validations.map((v) => v.run(req)));
        const errors = validationResult(req);
        if (errors.isEmpty()) {
            return next();
        }
        const msg = errors
            .array()
            .map((er) => `${er.param}`)
            .join(', ');
        const issue = new Issue(400, `missing or invalid params: ${msg}`);
        next(issue);
    };
}

The usage:

router.post(
    '/login',
    validation([body('email').isEmail(), body('password').isLength({ min: 5, max: 30 })]),
    async (req: Request, res: Response, next: NextFunction): Promise<void> => {
        ...
    });
``'