使用socket.ioparsingcookie

我试图正确地读取我的节点服务器上通过浏览器控制台localhost:3000上设置的cookie,如下所示:

document.cookie = "tagname = test;secure"; document.cookie = "hello=1" 

在我的节点服务器上,我使用sockets.io,当我得到一个连接请求,我可以访问一个属性,如下所示:

 socket.request.headers.cookie 

这是一个string,我总是看到这样的:

 'io=QhsIVwS0zIGd-OliAAAA' //what comes after io= is random. 

我试着翻译它与各种模块,但他们似乎无法parsingstring。 这是我最近的尝试:

 var cookie = require('cookie'); io.sockets.on('connection', function(socket) { socket.on('addUser', function(){ var a = socket.request.headers.cookie; var b = cookie.parse(a); //does not translate console.log(b); }); } 

我显然希望得到一个对象,包含浏览器上每个io.connect发送的所有cookie。 我一直试图解决它5个小时,我真的不知道我在这里做错了什么。

使用Cookie模块。 这正是你在找什么。

 var cookie = require('cookie'); 

cookie.parse(str,options)parsing一个HTTP Cookie头string并返回所有的Cookie名称 – 值对的一个对象。 str参数是表示Cookie标头值的string,options是包含附加parsing选项的可选对象。

 var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' } 

希望这可以帮助

没有正则expression式

 //Get property directly without parsing function getCookie(cookie, name){ cookie = ";"+cookie; cookie = cookie.split("; ").join(";"); cookie = cookie.split(" =").join("="); cookie = cookie.split(";"+name+"="); if(cookie.length<2){ return null; } else{ return decodeURIComponent(cookie[1].split(";")[0]); } } //getCookie('foo=bar; equation=E%3Dmc%5E2', 'equation'); //Return : "E=mc^2" 

或者,如果你想分析的cookie对象

 //Convert cookie string to object function parseCookie(cookie){ cookie = cookie.split("; ").join(";"); cookie = cookie.split(" =").join("="); cookie = cookie.split(";"); var object = {}; for(var i=0; i<cookie.length; i++){ cookie[i] = cookie[i].split('='); object[cookie[i][0]] = decodeURIComponent(cookie[i][1]); } return object; } //parseCookie('tagname = test;secure'); //Return : {tagname: " test", secure: "undefined"} 

尝试使用socket.handshake而不是socket.request

IO Cookie是socket.io用作用户标识的默认cookie。 你可以设置这个,但是如果你不这样做,它会创build一个并为其设置一个散列值。 阅读这里的选项。

我不认为这是一个代码问题。 这里是你的代码的一个例子。 当我添加cookietesting并将其设置为1

 var app = require('express')(); var http = require('http').Server(app); var cookie = require('cookie') var io = require('socket.io')(http); var port = process.env.PORT || 3000; app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.sockets.on('connection', function(socket) { socket.on('chat message', function(){ var a = socket.request.headers.cookie; var b = cookie.parse(a); //does not translate console.log(b); }); }); http.listen(port, function(){ console.log('listening on *:' + port); }); 

服务器输出

 { io: 'TxvLfvIupubZpOaGAAAF', test: '1' } 

如果我把它改成这个。

 var io = require('socket.io')(http, { cookie : 'id' }); 

输出会改变这个。

 { id: 'ZJPSwFsQAje0SrgsAAAD', test: '1' }