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

最新更新