我正在将现有的Hapi 16应用程序移植到Hapi 17 - 并且遇到了Joi验证的问题......
<!-- language: lang-js -->
'use strict';
const Joi = require('joi');
const validator = Joi.object({
"sku": Joi.string().required(),
"name": Joi.string()
// cut for berevity..
)
})
module.exports = {
method: ["POST", "PUT"],
path: "/api/products",
options: {
validate: {
params: validator
},
async handler(request, h) {
try {
const updateOrCreateItemQuery = { sku: request.payload.sku };
const result = await request.postItem( "product", updateOrCreateItemQuery);
return result;
} catch (err) {
throw h.internal("Internal MongoDB error", err);
}
}
}
};
当我启动应用程序时(而非我访问路线时),我收到以下错误:{ AssertionError [ERR_ASSERTION]: Cannot set path parameters validations without path parameters: POST /api/products
我已经把所有东西都剥夺了 - 所以它只是这条路线。它确实与Joi有关,就像我删除验证一样 - 它有效...我已经阅读了文档 - 并且无法看到我做错了什么......
(我已经将各种装饰器应用于请求对象 - 例如postItem等,...将项目发布到数据库中)
答案 0 :(得分:2)
<!-- language: lang-js -->
'use strict';
const Joi = require('joi');
const validator = {
"sku": Joi.string().required(),
"name": Joi.string()
// cut for berevity..
)
}
module.exports = {
method: ["POST", "PUT"],
path: "/api/products",
options: {
validate: {
payload: validator
},
async handler(request, h) {
try {
const updateOrCreateItemQuery = { sku: request.payload.sku };
const result = await request.postItem( "product", updateOrCreateItemQuery);
return result;
} catch (err) {
throw h.internal("Internal MongoDB error", err);
}
}
}
};
将validate转换为常规对象,并将validate选项设置为payload ....这是有道理的,因为这是一条此路由接受POST和PUT。