简体   繁体   中英

How to get specific cookie value in socket.io

I can now display the all cookie using socket.request.headers.cookie .

When I console the output is like this

PHPSESSID=mtklg8k81cpkop5ug6aechbb34; user=77; io=1Klg6xgTRXhb2OWiAAAA

How can I get only the user value which is 77? Code below give me an error undefined

var cookief = socket.request.headers.cookie;
console.log(cookief['user']);

You have to parse the cookies into their separate cookies and properties. The usual module to use for that is cookie-parser .

For use with socket.io, you can use a small wrapper with it for use with socket.io called socket.io-cookie-parser .

const cookieParser = require('socket.io-cookie-parser');
io.use(cookieParser());

io.on('connection', function(socket) {
    // access socket.request.cookies
    console.log(socket.request.cookies['user'];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM