Parsing cookies with socket.io Parsing cookies with socket.io node.js node.js

Parsing cookies with socket.io


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


Without Regexp

//Get property directly without parsingfunction 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 objectfunction 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"}


Try using socket.handshake instead of socket.request