Get SESSIONID in nodeJS

2019-07-12 17:37发布

Now, after some hours of playing around with nodejs and socket.io, I'm getting a couple more problems - one being, that I need to get the sessionID inside node.js, whitout using app.get('/' ... - since that event doesnt seem to fire when socket.io connects, it only fires .on('connection', function( ...

var express = require('express')()
express.set('port', process.env.PORT || 8080)

var server = require('http').createServer(express)
var socket = require('socket.io').listen(server)

server.listen(express.get('port'))

// this event is fired, get('/', ... isnt!
server.on('connection', function(stream) {
    // ??
} )

The Session is initially created by the PHP application, as the user logs in. Session data is stored in the database, and the key I need to access that data is the SESSION ID. What's the easiest way to get to it? Like mentioned, I found a couple examples that used app.get('/' ... but I couldnt get that event to fire at all.

Thanks.

1条回答
虎瘦雄心在
2楼-- · 2019-07-12 18:29

If the session data is being stored as a cookie (most likely), then you should be able to re-parse that data during the socket handshake. I posted code for that on this answer, but copied the code here as well:

io.configure(function () {
  io.set('authorization', function (handshakeData, callback) {

    var cookie = handshakeData.headers.cookie;

    // parse the cookie to get user data...

    // second argument to the callback decides whether to authorize the client
    callback(null, true);
  });
});

If the session data is being propagated in the URL, then you may be able to gather this information from handshakeData.url or handshakeData.query. You'll probably have to do your own experimentation.

查看更多
登录 后发表回答