繁体   English   中英

如何使用 JOI 验证请求正文中的对象数组

[英]How to validate an array of objects in a request body using JOI

我正在尝试验证所下订单的请求正文。 我在尝试验证的请求正文上收到一组 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 函数有什么问题,我将非常感激。

这似乎是一种奇怪的方法。 根据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(...)
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM