Express validator always returning error even when valid

74 Views Asked by At

I am using postman to send a post request with some data in the body, but express validator is always returning the error array. Here is the index.js code:

import express from "express";
import { router } from "./Routes/CreateUser.js";
import { connect, findFoodItems } from "./db.js";
import { body, validationResult } from "express-validator";


const app = express();
const port = 5000;

await connect();

app.get("/", (req, res) => {
    res.send("Hello World");
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

app.post('/createUser', body('name').notEmpty(), (req, res) => {
    const result = validationResult(req);
    if(result.isEmpty())
    {
        return res.send(`Hello ${req.body.name}`);
    }
    res.send({errors: result.array()});
});

I have tried everything but no matter what I do when I send a POST request to localhost50000/createUser whatever name value I give it always returns error array.

2

There are 2 best solutions below

0
On BEST ANSWER

You have to parse the body of response by using express middleware json and urlencoded

Express Doc

import express from "express";
import { router } from "./Routes/CreateUser.js";
import { connect, findFoodItems } from "./db.js";
import { body, validationResult } from "express-validator";


const app = express();
const port = 5000;

await connect();

app.use(express.json());    //this
app.use(express.urlencoded({extended:false})); 

app.get("/", (req, res) => {
    res.send("Hello World");
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

app.post('/createUser', body('name').notEmpty(), (req, res) => {
    const result = validationResult(req);
    if(result.isEmpty())
    {
        return res.send(`Hello ${req.body.name}`);
    }
    res.send({errors: result.array()});
});
0
On

Thanks everyone I figured out the solution, it was because in my createUser.js

import { User } from "../models/User.js";
import express from "express";
import {body, matchedData, validationResult } from "express-validator";
import bodyParser from "body-parser";

const router = express.Router();

const jsonParser = bodyParser.json();

router.post("/createUser",
    jsonParser,
    [
        body('name', 'Minimum length of name should be 5').isLength({ min: 5 }),
        body('email', 'Invalid email').isEmail(),
        body('password', 'Minimum length of password should be 5').isLength({min: 5}),
        body('location', 'Invalid location').isIn(['India', 'USA'])
    ],
    async (req, res) => {
        try {
            const result = validationResult(req);
            const data = matchedData(req);
            if(result.isEmpty())
            {
                await User.create({
                    name: data.name,
                    password: data.password,
                    email: data.email,
                    location: data.location
                });
                res.json({ success: true });
            }
            else
            {
                res.send({errors: result.array()});
            }
        } catch (error) {
            console.log(error);
            res.json({success: false});
        }   
    });

export { router };

I was reading body('name'), body('email'), etc BEFORE using bodyParser middleware but when I modified the code to use bodyParser middleware before express-validator middleware the express validator started working as expected. I am also sorry for not posting the createUser.js code but this was my first question and I will be more thorough next time.