什么可以是一个更好的方式来处理从nodejs项目中的控制器发送响应?

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调用是asynchronous的。 build议一些更好的做法来处理这种情况。

你是对的。 你不应该传递res对象。 它是一个debugging噩梦,如果有多个地方function可以退出。 后面的函数返回值并且控制器响应状态要好得多。

您可以简单地创build一个callback方法,一旦asynchronous数据库查询完成,将会调用该方法。 像这样的东西

 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'); } } }); } 

这是更新的代码

 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注入攻击