rooms.js - >房间端点的控制器类
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对象的原因是因为在控制器中执行res.status和res.send会产生问题,因为db调用是异步的。建议一些更好的做法来处理这种情况。
答案 0 :(得分:1)
这是更新后的代码
if (otp == otpInDb) {
console.log("User is authorised");
res.json({
status:200,
message:"user authorized"
})
} else {
res.json({
status:401,
message:"user not authorized"
})
}
最好以信封形式发送回复。我可以看到你正在使用String
类似的查询。使用sequelize之类的orm包装来防止SQL注入攻击
答案 1 :(得分:1)
你是对的。您不应传递res
对象。如果函数可以退出的位置不止一个,那么这是一个调试的噩梦。后续函数返回值并且控制器响应状态要好得多。
您可以简单地创建一个回调方法,该方法将在异步数据库查询完成后调用。像这样的东西
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);
});
并且main函数可以调用此函数
//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');
}
}
});
}