use*_*653 13 javascript sockets cookies io node.js
我试图通过localhost:3000上的浏览器控制台正确读取我的节点服务器上的cookie,如下所示:
document.cookie = "tagname = test;secure";
document.cookie = "hello=1"
Run Code Online (Sandbox Code Playgroud)
在我的节点服务器中,我使用sockets.io,当我收到连接请求时,我可以访问如下所示的属性:
socket.request.headers.cookie
Run Code Online (Sandbox Code Playgroud)
这是一个字符串,我总是这样看:
'io=QhsIVwS0zIGd-OliAAAA' //what comes after io= is random.
Run Code Online (Sandbox Code Playgroud)
我试图用各种模块翻译它,但它们似乎无法解析字符串.这是我最近的尝试:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
我显然希望获得一个对象,其中包含浏览器上每个io.connect发送的所有cookie.我一直试图解决它5个小时,我真的不知道我在这里做错了什么.
noa*_*ale 12
使用Cookie模块.这正是你要找的.
var cookie = require('cookie');
Run Code Online (Sandbox Code Playgroud)
cookie.parse(str,options)解析HTTP Cookie头字符串并返回所有cookie名称 - 值对的对象.str参数是表示Cookie标头值的字符串,options是包含其他解析选项的可选对象.
var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
// { foo: 'bar', equation: 'E=mc^2' }
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
没有正则表达式
//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"
Run Code Online (Sandbox Code Playgroud)
或者,如果您想将 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"}
Run Code Online (Sandbox Code Playgroud)