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