【问题标题】:How to validate an array of objects in a request body using JOI如何使用 JOI 验证请求正文中的对象数组
【发布时间】:2020-06-30 01:34:56
【问题描述】:

我正在尝试验证所下订单的请求正文。我在尝试验证的请求正文上收到了一组 json 对象。每次我收到错误“需要“productId””

这是我的请求正文:

req.body={
    "productId": [
        { "id": "5dd635c5618d29001747c01e", "quantity": 1 },
        { "id": "5dd63922618d29001747c028", "quantity": 2 },
        { "id": "5dd635c5618d29001747c01e", "quantity": 3 }
    ]
}

这里是验证请求正文的 valdateOrder 函数:

function validateOrder(req.body) {
    const schema = {

        productId: joi.array().items(
            joi.object().keys({
                id: joi.string().required(),
                quantity: joi.string().required()
            })).required(),
    }

    return joi.validate(req.body, schema)

}

如果有人能指出我的 validateOrder 函数有什么问题,我将非常感激。

【问题讨论】:

  • 您在路由前使用的是express.json() 还是bodyParser.json()?你能console.log(req.body)吗?
  • 是的,我正在使用 express.json()。 Joi 验证在除此路线之外的所有其他路线中运行顺利。我觉得我在验证对象数组时犯了一些错误。
  • 天哪。我刚刚去了console.log(req.body),发现我将“req”传递给了validateOrder(req) 而不是req.body。不敢相信我在这个最小的错误上一直摸不着头脑超过三个小时。解决了。​​
  • 谢谢@cbr :)
  • 如果您对自己的解决方案感到满意,您可以回答自己的问题!我建议您查看下面 Mike 的答案,以了解有关构建应用程序的好方法的示例。

标签: javascript node.js mongodb express joi


【解决方案1】:

这似乎是一种奇怪的方式。根据https://hapi.dev/module/joi/,将您的架构定义为自己的东西,然后使用该架构验证您的数据:

const Joi = require('@hapi/joi');

const schema = Joi.object({
  productId: Joi.array().items(
    Joi.object(
      id: Joi.string().required(),
      quantity: Joi.number().required()
    )
  )
};

module.exports = schema;

然后您在路由中间件中使用它进行验证:

const Joi = require('@hapi/joi');
const schema = require(`./your/schema.js`);

function validateBody(req, res, next) {
  // If validation passes, this is effectively `next()` and will call
  // the next middleware function in your middleware chain.

  // If it does not, this is efectively `next(some error object)`, and
  // ends up calling your error handling middleware instead. If you have any.

  next(schema.validate(req.body));
}

module.exports = validateBody;

你在 express 中使用的和其他中间件一样:

const validateBody = require(`./your/validate-body.js`);

// general error handler (typically in a different file)
function errorHandler(err, req, res, next) {
  if (err === an error you know comes form Joi) {
    // figure out what the best way to signal "your POST was bad"
    // is for your users
    res.status(400).send(...);
  }
  else if (...) {
    // ...
  }
  else {
    res.status(500).send(`error`);
  }
});

// and then tell Express about that handler
app.use(errorHandler);

// post handler
app.post(`route`, ..., validateBody, ..., (req, res) => {
  res.json(...)
});

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2018-05-25
    • 2021-09-06
    • 2020-08-29
    相关资源
    最近更新 更多