最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js socket.io get cookie value - Stack Overflow

programmeradmin3浏览0评论

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

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
 });
Share Improve this question asked Oct 24, 2015 at 8:15 Максим ЗубковМаксим Зубков 6352 gold badges8 silver badges23 bronze badges 2
  • Possible duplicate of Can I access a cookie from Socket.io? – laggingreflex Commented Oct 24, 2015 at 8:19
  • 1 @laggingreflex no body answer socket.handshake.headers.cookie – Максим Зубков Commented Oct 24, 2015 at 8:32
Add a comment  | 

1 Answer 1

Reset to default 16

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' }
发布评论

评论列表(0)

  1. 暂无评论