MySQL和express.socket.io-session,函数之外的变量

时间:2018-01-05 19:30:04

标签: node.js socket.io

更新了代码以显示我所做的事情。我无法从.session.userdata

获取具体信息
// Socket stuff
io.use(sharedsession(session));
io.on('connect', function (socket) {
    var str = JSON.stringify(socket.handshake.session.passport);
    str = JSON.stringify(socket.handshake.session.passport, null, 4);

    // console.log(str);
    var query = db.query('SELECT * FROM users WHERE id = ?', socket.handshake.session.passport.user, function (err, row) {
      if (err) {
        throw err;
      } else {
        console.log(row) // added 
        socket.handshake.session.userdata = row;
        socket.handshake.session.save();
        var dataObj = socket.handshake.session.userdata;
        socket.emit('startup', dataObj);
      }
    });

    // Server Time
    var interval = setInterval(function () {
        var momentNow = moment();
        var data = momentNow.format('LT');
        socket.emit('time', data);
      }, 60000);

    // Chat - Needs work
    socket.on('chat', function (msg) {
      console.log(socket.handshake.session.userdata.username);
      var message = msg;

      // username = req.user.username;
      io.emit('message', message);
    });

    socket.on('disconnect', function () {
      if (socket.handshake.session.userdata) {
        delete socket.handshake.session.userdata;
        socket.handshake.session.save();
      }

      console.log('user disconnected');
    });

  });

我为行本身添加了一个控制台日志,后面是数据包:

[ RowDataPacket {
    id: 3,
    username: 'test',
    password: '$2a$10$BGKL6fyTbZ3bwVCfSmj3Iu6OGBAryV.qkDNeHsRD/enCbldCW.PuC',
    email: 'test@test.test',
    rank: 1,
    title: 'Squire',
    kills: 0,
    deaths: 0,
    medals: 0,
    silver: 100,
    kingname: 'test',
    str: 5,
    tough: 5,
    speed: 5,
    accur: 5,
    farmlevel: 1,
    food: 0,
    minelevel: 1,
    iron: 0,
    stonelevel: 1,
    stone: 0,
    lumberlevel: 1,
    lumber: 0 } ]

1 个答案:

答案 0 :(得分:1)

您的row变量是一个数组,而不是单个值。您需要索引该数组才能获得单个userData对象。

改变这个:

socket.handshake.session.userdata = row;

到此:

socket.handshake.session.userdata = row[0];

您可能需要检查数组的长度以确保它不为空(这取决于查询无法找到任何数据时数据库的行为方式)。