node.jsexpressexpress-validator

Express validator always returning error even when valid


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.


Solution

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