Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing cookies with socket.io

I am trying to properly read cookies on my node server that were set by me through the browser console on localhost:3000 like this:

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

In my node server, I use sockets.io, and when I get a connection request, I can access a property which goes like this:

socket.request.headers.cookie   

It's a string, and I always see it like this:

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

I've tried to translate it with various modules but they can't seem to parse the string. this is my latest attempt:

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);
    });
}       

I obviously want to get an object with all the cookies that were sent by each io.connect on the browser. I've been trying to solve it for 5 hours and I really don't know what I am doing wrong here.

like image 940
user1938653 Avatar asked Sep 01 '16 12:09

user1938653


2 Answers

Use the Cookie module. It is exactly what you are looking for.

var cookie = require('cookie');

cookie.parse(str, options) Parse an HTTP Cookie header string and returning an object of all cookie name-value pairs. The str argument is the string representing a Cookie header value and options is an optional object containing additional parsing options.

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

Hope this helps

like image 63
deadlock Avatar answered Sep 20 '22 09:09

deadlock


Without Regexp

//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"

Or if you want to parse the cookie to object

//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"}
like image 20
StefansArya Avatar answered Sep 19 '22 09:09

StefansArya