Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js socket.io get cookie value

i want to get cookie value in node server with socket.io

so every time socket send message to server i check the value of cookie

(i don't want session cookie) only in express i get the cookie by

 router.get('/', function(req, res, next) {

  var cookie_id = req.cookies.userIDf;
  console.log(cookie_id);
   res.render('index', { title: 'Express' });
});

its work here but with socket.io i cant get cookie any solution ?

io.sockets.on('connection', function (socket) {


var cookief =socket.handshake.headers['cookie'];
  console.log(cookief); // its give me session  id not the cookies
 });
like image 287
Максим Зубков Avatar asked Oct 24 '15 08:10

Максим Зубков


1 Answers

You can use the cookie module to do this.

npm install --save cookie

var cookie = require("cookie") //installed from npm;

io.on('connection', function (socket) {
    
    var cookief = socket.handshake.headers.cookie; 
    var cookies = cookie.parse(socket.handshake.headers.cookie);    

});

cookief will return, but isn't accessible as a JSON object.

 io=5J1m_uXsDZvc61gTAAAA; userID=63kfh16tiu7md3ck7djv8856s0; userIDf=50

cookies, which parses cookief using cookie.parse(), will allow allow you to access each of the cookie values as a JSON object:

 cookies.io; //Returns 5J1m_uXsDZvc61gTAAAA
 cookies.userID; //Returns 63kfh16tiu7md3ck7djv8856s0
 cookies.userIDf; //Returns 50

or

 { io: 'RqIksBUQW4SM4zA4AAAA', userID: '63kfh16tiu7md3ck7djv8856s0', userIDf: '50' }
like image 198
Максим Зубков Avatar answered Nov 03 '22 22:11

Максим Зубков