TypeError:无法调用方法'获取'在socket.handshake上未定义的

TypeError: Cannot call method 'get' of undefined at socket.handshake

本文关键字:handshake socket 未定义 获取 方法 调用 TypeError      更新时间:2023-09-26

我正在尝试将socket.io代码从0.9v重建为1.x。Express和socket.io是最新版本。

因此,错误:处的Cannot call method 'get' of undefined

 io.on('connection', function(socket) {
            console.log(socket.handshake);
            var username = socket.handshake.user.get('username'); //<----here
            ......

这是我的代码:

module.exports = function(server) {
                var io = require('socket.io')(server);
                io.set('origins', 'localhost:*');
            //I changed set to use, but it's doesn't matter i think
                io.use(function(socket, next) {  
                    var handshake = socket.request;
                //io.set('authorization', function(handshake, callback) {
                    async.waterfall([
                        function(callback) {
                         handshake.cookies = cookie.parse(handshake.headers.cookie || '');
     var sidCookie = handshake.cookies[config.get('session:key')];
      var sid = connect.utils.parseSignedCookie(sidCookie, config.get('session:secret'));
      //var sid = cookieParser.signedCookie(sidCookie, config.get('session:secret'));
                            loadSession(sid, callback);
                        },  ...continue...

续:

function(session, callback) {
                            if (!session) {
                                callback(new HttpError(401, "No session"));
                            }
                            handshake.session = session;
                            loadUser(session, callback);
                        },
                        function(user, callback) {
                            if (!user) {
                                callback(new HttpError(403, "Anonymous session may not connect"));
                            }
                            handshake.user = user;
                            callback(null);
                        }
                    ], function(err) {.....});
                next();
                });
        io.on('connection', function(socket) { ... };

返回io;};

好的,请帮帮我,谢谢!

我将如何调试它。无法对未定义的东西调用方法

所以我们知道,调用.get的东西还没有创建。在这种情况下:

var username = socket.handshake.user.get('username'); //<----here

因此,如果你不能访问ide调试器,我会做的第一件事就是

控制台.log(套接字)

如果有数据

console.log(套接字握手);

如果有数据

console.log(套接字握手用户);

如果它有数据,请检查它是否有GET方法。

无论如何,我的假设是socket.handshake.user还没有定义。设置/公开它的代码在哪里?