yup req.body is undefined in middleware function

Issue

Im trying to validate my data from my express endpoint with yup. After watching several tutorials I´m stuck with the following error.

If I try to validate my data in my middleware, it always returns an error. After logging req.body I noticed, it was undefined.

Here are my following methods (all in different files). My schema looks like this:

const loginSchema = yup.object({
    body: yup.object({
        email: yup.string().email().required(),
        password: yup.string().min(3).max(16).required()
    })
})

module.exports = loginSchema;

My validation middleware function looks like this:

const validation = (schema) => async (req, res, next) => {
    console.log(JSON.stringify(req.body)) // is undefined
    try {
        await schema.validate({
            body: req.body
        });

        return next();
    } catch(err) {
        res.status(400).json({err})
    }
};

module.exports = validation;

And my endpoint in my express.js backend looks like this:

// validation and schemas has been imported
 
router.post("/login", validation(schemas), (req, res) => {
    // some code
})

And if I try to validate my data after sending a post request, it always returns the following:

{
    "err": {
        "value": {
            "body": {}
        },
        "path": "body.password",
        "type": "required",
        "errors": [
            "body.password is a required field"
        ],
        "params": {
            "path": "body.password"
        },
        "inner": [],
        "name": "ValidationError",
        "message": "body.password is a required field"
    }
}

Has anyone had the same issue ? Because I didn´t find anything about this kind of error.
I used this pattern : https://dev.to/franciscomendes10866/schema-validation-with-yup-and-express-js-3l19

Solution

You need to use the body-parser package to read the ‘req.body’.

install the package and use it in your server.js file.

npm install body-parser

import bodyParser from "body-parser";

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

Answered By – Krishna

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published