我只想在Joi API中实现Hapi

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 requiredDebug: 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)

最佳答案

作为错误提示,在处理程序只能返回错误,接管响应或必须返回接管响应的继续信号之前调用的Lifecycle方法。

return h.response({ code: 0, message: source.details[0].message }).takeover();


有关更多信息,您可以访问以下链接:reference link

关于node.js - 如何在hapi.js中实现Joi验证?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59663656/

10-12 18:06