learnbasic
learnbasic

Reputation: 35

JOI [ValidationError] when validating req.body

Hello I am learning the basics of node. The issue im having is that I want to validate the data passed into the post request from a html form. The data is being passed in but im also getting an error in the console.

Here is the server code:

app.post('/', (req, res)=> {
    const schema = Joi.object({
        username: Joi.string().trim().required(),
        password: Joi.string().min(3).max(10).required(),
    })

    const validation = schema.validate(req.body);
    console.log(req.body)

    if(validation.error){
        console.log(validation.error)
        // res.send('an error has occurred')
    }
    res.send('successfully posted data')
})

the console error (with sample data: username: test & password: test):

[Error [ValidationError]: "value" must be of type object] {
  _original: [
    { name: 'username', value: 'test' },
    { name: 'password', value: 'test' }
  ],
  details: [
    {
      message: '"value" must be of type object',
      path: [],
      type: 'object.base',
      context: [Object]
    }
  ]
}

I dont understand why I am getting a validation error. The req.body appears to be an object when printed to the console with console.log(req.body) but when I try to use validation it appears inside of an array? Kind of confused.

Additional Info: I am using express.urlencoded() and express.json() if that matters.

Here is the JQuery from the HTML page:

    <script>
        $(document).ready(()=>{
            $('#form').submit((e)=>{
                e.preventDefault();
                $.ajax({
                    url: '/',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify($('#form').serializeArray()),
                    success: (response)=>{
                        console.log('successfully got response');
                        console.log(response)
                    }
                })
            })
        });
    </script>

Upvotes: 0

Views: 2272

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

The error clearly states that req.body is an array.

[
    { name: 'username', value: 'test' },
    { name: 'password', value: 'test' }
]

From jQuery documentation page, we also have .serializeArray() method creates a JavaScript array of objects. So, you're actually sending an array of objects to the server-side and that's why you have the error.

To fix the problem, I think you should modify the frontend part. Since you already have express.urlencoded(), you can use serialize.

  <script>
        $(document).ready(()=>{
            $('#form').submit((e)=>{
                e.preventDefault();
                $.ajax({
                    url: '/',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify($('#form').serialize()),
                    success: (response)=>{
                        console.log('successfully got response');
                        console.log(response)
                    }
                })
            })
        });
    </script>

Upvotes: 1

Related Questions