如何使用 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(...)
});