2

我只想JoiHapiAPI 中实现。

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)

4

1 回答 1

4

正如错误提示在处理程序之前调用的生命周期方法只能返回错误、接管响应或继续信号,您必须返回接管响应。

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

有关更多信息,您可以访问此链接:参考链接

于 2020-01-10T05:17:49.890 回答