rooms.js -> 房间端点的 Controller 类
router.get('/:roomid/fight/verify', function(req, res) {
roomModel.authenticateUserForFight(req.params.roomid, req.query.otp, res);
});
roomModel -> 房间模型类
//authenticate user based on otp provided on client side
exports.authenticateUserForFight = function(roomid, otp, res) {
db.query('select * from room where roomid=?', [roomid], function(error, rows) {
if (rows.length == 0) {
console.log("otp does not exist in db for room:" + roomid);
} else if (rows.length == 1) {
var otpInDb = rows[0].otp.toString();
if (otp == otpInDb) {
console.log("User is authorised");
res.status(200);
res.send("User is authorised");
} else {
console.log("User is unauthorised");
res.status(401);
res.send("User not authorised");
}
}
});
}
这段代码工作正常,但是有没有更好的方法来向客户端发送响应,而不是将 res 对象传递给模型类并在那里设置状态和响应消息?我传递 res 对象的原因是因为在 Controller 中执行 res.status 和 res.send 会出现问题,因为数据库调用是异步的。建议一些更好的做法来处理此类情况。
最佳答案
你是对的。您不应传递 res
对象。如果函数可以从多个地方退出,那么这将是一场调试噩梦。最好是后续函数返回值并且 Controller 响应状态。
您可以简单地创建一个回调方法,异步数据库查询完成后将调用该方法。像这样的事情
router.get('/:roomid/fight/verify', function(req, res) {
const callback = (status, message) => {
res.status = status
res.send(message);
}
roomModel.authenticateUserForFight(req.params.roomid, req.query.otp, callback);
});
主函数可以直接调用这个函数
//authenticate user based on otp provided on client side
exports.authenticateUserForFight = function(roomid, otp, callback) {
db.query('select * from room where roomid=?', [roomid], function(error, rows) {
if (rows.length == 0) {
console.log("otp does not exist in db for room:" + roomid);
} else if (rows.length == 1) {
var otpInDb = rows[0].otp.toString();
if (otp == otpInDb) {
console.log("User is authorised");
callback(200, 'user authorized');
} else {
console.log("User is unauthorised");
callback(401, 'user not authorized');
}
}
});
}
关于node.js - 在 Nodejs 项目中处理 Controller 发送响应的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532462/