首页 > 解决方案 > 我如何控制错误,猫鼬

问题描述

这是一场私人比赛,游戏有2名玩家,名字和密码,如果你想加入你必须匹配他们。

问题是:我如何控制匹配或名称不匹配或游戏已经满员,以便我可以向客户端发送不同的消息?如果有人可以向我展示另一个有用的帖子或一些文档链接可以帮助我,我会非常高兴。

谢谢

exports.joinPrivateMatch = (req, res) =>{
let gamePass = req.body.password;
let gameName = req.body.name;
let playerid = req.body.playerid;
let socketPID = req.body.socketid;

creatematch.findOneAndUpdate({player2: null, name: gameName, password: gamePass}, {
    player2: playerid,
    socketID2: socketPID
}, {new:true}, function(err, result){
    if(result){
        res.send(result);
        ioConnection.to(`${result.socketID1}`).emit('addplayer2', result);
        ioConnection.to(`${result.socketID1}`).emit('matchfull', /*{ScreenReady: true} */);
        ioConnection.to(`${result.socketID2}`).emit('matchfull', /*{ScreenReady: false} */);
    }
    if(err){
        return res.send('something went wrong', err)
    }
    else{
        console.log('Contraseña incorrecta o partida llena')
        ioConnection.to(`${socketPID}`).emit('sadsmiley')
    }
})

我写了这样的东西:

 if(name != gameName || password != gamePass){
console.log("name or password doesnt match")
ioConnection.to(`${socketPID}`).emit('findError1')
}

但只要我没有得到响应,名称和密码将是未定义的。

标签: javascriptmongodbmongoose

解决方案


您可以为此目的使用 Express 中间件...请参阅使用 Express 中间件

var app = express()
var router = express.Router()

// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  //here implement code for matching gameName & Password
  //if not match, return authentication error response
  //else pass the control to the next function 
  next()
})

推荐阅读