【问题标题】:JOI [ValidationError] when validating req.body验证 req.body 时的 JOI [ValidationError]
【发布时间】:2021-06-26 15:15:55
【问题描述】:

您好,我正在学习节点的基础知识。我遇到的问题是我想验证从 html 表单传递到 post 请求的数据。数据正在传入,但控制台中也出现错误。

这是服务器代码:

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')
})

控制台错误(带有示例数据:用户名:test & 密码: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]
    }
  ]
}

我不明白为什么会出现验证错误。当使用 console.log(req.body) 打印到控制台时, req.body 似乎是一个对象,但是当我尝试使用验证时,它出现在数组内部?有点困惑。

附加信息: 如果这很重要,我正在使用 express.urlencoded()express.json()

这是来自 HTML 页面的 JQuery:

    <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>

【问题讨论】:

    标签: node.js express validation joi


    【解决方案1】:

    错误明确指出req.body 是一个数组。

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

    来自jQuery documentation page,我们还有.serializeArray() method creates a JavaScript array of objects。因此,您实际上是在将一组对象发送到服务器端,这就是您遇到错误的原因。

    要解决这个问题,我认为你应该修改前端部分。既然你已经有了 express.urlencoded(),你可以使用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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2018-09-24
      • 2018-02-03
      • 1970-01-01
      • 2013-10-19
      • 2017-07-28
      • 2021-02-05
      相关资源
      最近更新 更多