我正在使用hapi和猫鼬来简化登录系统。
server.route({
method: 'POST',
path: '/register',
config: {
handler: (request, h) => {
const username = request.payload.username.toLowerCase();
const email = request.payload.email.toLowerCase();
const password = request.payload.password;
const passwordconfirm = request.payload.passwordconfirm;
if(password==passwordconfirm && username && email && password) {
var userData = {
email: email,
username: username,
password: password,
verified: false
}
User.create(userData, function (err, user) {
//if there is an error about email
if (err.toString().indexOf("email")>-1) {
return statusGenerator(false, "Email already in use", null);
}
//if there is an error about email
if (err.toString().indexOf("username")>-1) {
return statusGenerator(false, "Username already in use", null);
}
//send email to specified email
return statusGenerator(true,"Confirm your email",null);
});
}
}
}
});
statusGenerator()生成一个JSON,该JSON应该作为响应发送回。
在hapi中,我可以从处理程序中返回以实现此目的,但我不知道如何从回调中获取该值并作为响应发送。
这是错误。
Debug: internal, implementation, error
Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (c:\Users\me\path\node_modules\hapi\lib\toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
最佳答案
我使用Promise解决了它:
return new Promise((resolve) => {
User.create(userData, function (err, user) {
if(err)
{
if (err.toString().indexOf("email")>-1) {
resolve(statusGenerator(false, "Email already in use", null));
}
if (err.toString().indexOf("username")>-1) {
resolve(statusGenerator(false, "Username already in use", null));
}
}
//send email to specified email
resolve(statusGenerator(true,"Confirm your email",null));
});
});
关于node.js - NodeJS:Hapi + Mongoose |返回回调不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51002846/