node.js 我可以从 Socket.io 访问 cookie 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4754232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I access a cookie from Socket.io?
提问by Dan
I want to set some user information in a cookie and be able to access it on connection, is this possible?
我想在 cookie 中设置一些用户信息并能够在连接时访问它,这可能吗?
采纳答案by Shripad Krishna
client.request.headers.cookieleads to race conditions as the cookie always points to the last logged in user.
client.request.headers.cookie导致竞争条件,因为 cookie 总是指向最后登录的用户。
Please see: Socket.IO Authentication.
请参阅:Socket.IO 身份验证。
回答by gabrtv
Using Socket.IO 0.8.7, you can access request headers via:
使用 Socket.IO 0.8.7,您可以通过以下方式访问请求标头:
socket.handshake.headers
socket.handshake.headers
You can find more detail on this at https://github.com/LearnBoost/socket.io/wiki/Authorizing
您可以在https://github.com/LearnBoost/socket.io/wiki/Authorizing上找到更多详细信息
回答by Dan
I got it, this works:
我明白了,这有效:
client.request.headers.cookie
回答by gilbert
After looking to the engine.io source code you can set cookies using:
查看 engine.io 源代码后,您可以使用以下方法设置 cookie:
var io = require('socket.io')(3000);
io.use((socket, next) => {
socket.conn.transport.once('headers', (headers) => {
headers['set-cookie'] ="sess=test;"; });
next();
});
this code could conflict with the engine.io code that set the sid cookie. as both HTTP/1.1 and HTTP/2 headers are case-insensitive and engine.io use 'Set-Cookie' in the headers object adding a lowercase object name 'set-cookie' would avoid this problem.
此代码可能与设置 sid cookie 的 engine.io 代码冲突。因为 HTTP/1.1 和 HTTP/2 标头都不区分大小写,并且 engine.io 在标头对象中使用“Set-Cookie”,添加小写对象名称“set-cookie”可以避免这个问题。

