如何在 hapi.js 中实现 Joi 验证?
How to implement Joi validation in hapi.js?
我只想在 Hapi
API 中实现 Joi
。
server.route([
{
method: 'POST',
path: '/login',
config: {
tags: ['login', 'auth'],
auth: false,
validate: {
payload: payloadValidator,
failAction: (req, h, source, error) => {
console.log("Error ::: ", source.details[0].message);
return h.response({ code: 0, message: source.details[0].message });
}
}
},
handler: async (request, h) => {
console.log(request.payload.email);
console.log(request.payload.password);
...
}
}
]);
听到我的声音 payloadValidator
。
const payloadValidator = Joi.object({
email: Joi.string().required(),
password: Joi.string().required()
}).options({ allowUnknown: true });
实际上我是 hapi
的新手,我的代码中遗漏了一些东西。谁能帮我解决这个问题?
需要输出
如果我没有通过 email
那么应用程序必须抛出一个错误 Email is required
并且它也应该与 password
字段相同。
错误:
Error ::: "email" is required
Debug: internal, implementation, error
Error: Lifecycle methods called before the handler can only return an error, a takeover response, or a continue signal
at Request._lifecycle (/var/www/html/hapi/node_modules/@hapi/hapi/lib/request.js:326:33)
at process._tickCallback (internal/process/next_tick.js:68:7)
如错误提示在处理程序只能return错误、接管响应或继续信号之前调用的生命周期方法,您必须return 接管响应。
return h.response({ code: 0, message: source.details[0].message }).takeover();
有关更多信息,您可以访问此 link:reference link
我只想在 Hapi
API 中实现 Joi
。
server.route([
{
method: 'POST',
path: '/login',
config: {
tags: ['login', 'auth'],
auth: false,
validate: {
payload: payloadValidator,
failAction: (req, h, source, error) => {
console.log("Error ::: ", source.details[0].message);
return h.response({ code: 0, message: source.details[0].message });
}
}
},
handler: async (request, h) => {
console.log(request.payload.email);
console.log(request.payload.password);
...
}
}
]);
听到我的声音 payloadValidator
。
const payloadValidator = Joi.object({
email: Joi.string().required(),
password: Joi.string().required()
}).options({ allowUnknown: true });
实际上我是 hapi
的新手,我的代码中遗漏了一些东西。谁能帮我解决这个问题?
需要输出
如果我没有通过 email
那么应用程序必须抛出一个错误 Email is required
并且它也应该与 password
字段相同。
错误:
Error ::: "email" is required
Debug: internal, implementation, error
Error: Lifecycle methods called before the handler can only return an error, a takeover response, or a continue signal
at Request._lifecycle (/var/www/html/hapi/node_modules/@hapi/hapi/lib/request.js:326:33)
at process._tickCallback (internal/process/next_tick.js:68:7)
如错误提示在处理程序只能return错误、接管响应或继续信号之前调用的生命周期方法,您必须return 接管响应。
return h.response({ code: 0, message: source.details[0].message }).takeover();
有关更多信息,您可以访问此 link:reference link