NODE JS Socket IO:req,res

时间:2015-09-27 11:25:43

标签: javascript node.js sockets session express

我在我的网站上使用节点js和套接字io我有一个问题,当我的“client.on('Connexion',function(data){}”被调用时,我想在我的网站上连接我的客户端,并且我有一个问题:

/* ------- CALLBACK CONNECTION : --------*/

io.sockets.on('connection', function (client, req, res) {

  client.on('Connexion', function(data) {
        blabla...
        if(results[0]) {
          req.session.id = results[0];
          req.session.firstname = results[1];
          req.session.lastname = results[2];
          req.session.email = results[4];
          req.session.birthdate = results[5];
          req.session.phonenum = results[6];
          res.redirect("http://mydomain/" + "espace-client/");
                          
          /* HERE, req.session give and error --> TypeError: Cannot read property 'session' of undefined */ 
         }           
    }
});
  
 
/* ------- I HAVE TEST THIS AND IT WORKS FINE : --------*/
  
app.get('/test/', function(req, res) {
   req.session.id = "45";
   res.send(req.session.id);
});

提前谢谢你:)

1 个答案:

答案 0 :(得分:0)

您可以尝试这样做:

    const io = socketIO.listen(server);
io.sockets
  .on('connection', socket => {
    socket.on('socket.setOnline', async event => {
      const { access_token } = event;

      if (!access_token) return socket.emit('socket.error', 'no access_token token');

      jwt.verify(access_token, 'HelloThere', err => {
        if (err) socket.emit('socket.error', err.message);
      });

      const user = await userService.getByAccessToken(access_token);

      if (!user) return socket.emit('socket.error', 'user on setOnline not found');

      user.update({ isOnline: true });

      socket.emit('socket.notification', `#${user.id}: ${user.name} is online`);
      socket.emit('socket.userStatus', { status: 'online' })
    })

    socket.on('socket.setOffline', async event => {
      const { access_token } = event;

      if (!access_token) return socket.emit('socket.error', 'no access_token token');

      jwt.verify(access_token, 'HelloThere', err => {
        if (err) socket.emit('socket.error', err.message)
      });

      const user = await userService.getByAccessToken(access_token);

      if (!user) return socket.emit('socket.error', 'user on setOffline not found');

      user.update({ isOnline: false });

      socket.emit('socket.notification', `#${user.id}: ${user.name} is offline`);
      socket.emit('socket.userStatus', { status: 'offline' })
    })
    socket.on('socket.checkUserStatus', async event => {
      const { access_token } = event;

      if (!access_token) return socket.emit('socket.error', 'no access_token token');

      jwt.verify(access_token, 'HelloThere', err => {
        if (err) socket.emit('socket.error', err.message);
      });

      const user = await userService.getByAccessToken(access_token);

      socket.emit('socket.userStatus', { status: user.isOnline ? 'online' : 'offline' })
    })
  })