读取socket.request.session.passport.user的属性时出错,无法读取未定义的属性

时间:2019-06-07 04:53:09

标签: node.js mongodb express session passport.js

我正在创建一个创建聊天室的应用程序。在获取活动用户列表时,我编写了帮助程序代码,用于将当前会话处于活动状态的用户添加到rooms数组中,我的helpers.js文件具有以下功能: helpers.js

let addUserToRoom = (allrooms, data, socket) => {
    let getRoom = findRoomById(allrooms, data.roomID);
    if (getRoom !== undefined) {
        let userID = socket.request.session.passport.user;

        let checkUser = getRoom.users.findIndex((element, index, array) => {
            if(element.userID === userID) {
                return true;
            } else {
                return false;
            }
        });

        if (checkUser > -1) {
            getRoom.users.splice(checkUser, 1);
        }

        getRoom.users.push({
            socketID: socket.id,
            userID,
            user: data.user,
            userPic: data.userPic
        });

        socket.join(data.roomID);
        return getRoom;
    }
}

上面的代码找出用户是否已经在房间里。如果是,则删除该用户并将其读入加入的用户列表。但是在测试此代码时,出现以下错误:

/home/shacker/Programs20182/aanjs/chatcat/app/helpers/index.js:102
        let userID = socket.request.session.passport.user;
                                                     ^

TypeError: Cannot read property 'user' of undefined
    at Object.addUserToRoom (/home/shacker/Programs20182/aanjs/chatcat/app/helpers/index.js:102:54)
    at Socket.socket.on.data (/home/shacker/Programs20182/aanjs/chatcat/app/socket/index.js:29:30)
    at Socket.emit (events.js:189:13)
    at /home/shacker/Programs20182/aanjs/chatcat/node_modules/socket.io/lib/socket.js:528:12
    at process._tickCallback (internal/process/next_tick.js:61:11)

还有其他方法可以从会话中获取userID变量,还是可以帮助我删除该错误...

0 个答案:

没有答案