【问题标题】:Send cookies with socket.io-client使用 socket.io-client 发送 cookie
【发布时间】:2017-04-27 16:45:28
【问题描述】:

我正在尝试连接到 websocket。我想从实际的网站登录中添加 cookie,以便服务器(不是我的)知道我是谁(事件是特定于帐户的)。

var opts = {
   extraHeaders: {
        'Cookie': "_ga=GA1.2.17432343994.1475611967; _gat=1; __cfduid=dc232334gwdsd23434542342342342475611928"
    },
}

function socket() {
            var socket = io(websiteURL, opts);
            var patch = require('socketio-wildcard')(io.Manager); patch(socket);

            socket.on('connect', function () {
                console.log(" > [Connected]");

            });
            socket.on('*', function (data) {                
                console.log(" >>> " + data);
            });

            socket.on('disconnect', function () {
                console.log(" > [Disconnected]");
            });

}

连接本身工作正常,因为我从网站接收公共事件(不是每个帐户的)。

我尝试使用节点检查器查找问题。

这是正在完成的第一个请求。看起来请求标头是空的,并且那里缺少 cookie。

节点检查器:

网站在chrome中的正常使用:

(是的,我在节点中发送的 cookie 较少,只是为了查看它们是否会在请求 cookie 中弹出)

我做错了吗?如何以正确的方式添加 cookie?

【问题讨论】:

    标签: node.js websocket socket.io client


    【解决方案1】:

    我遇到了类似的问题,我认为您的选项必须为“轮询”传输方法设置 cookie,如下所示:

    var opts = {
        transportOptions: {
            polling: {
                extraHeaders: {
                    'Cookie': '_ga=GA1.2.17432343994.1475611967; _gat=1; __cfduid=dc232334gwdsd23434542342342342475611928'
                }
            }
        }
    }
    

    我让它与以下多合一服务器-客户端示例一起使用:

    const express = require('express');
    const http = require('http');
    
    const app = express();
    const httpServer = new http.Server(app);
    const socketServer = require('socket.io')(httpServer);
    
    const LISTEN_PORT = 4444;
    
    socketServer.on('connection', socket => {
        const cookieString = socket.handshake.headers.cookie;
        console.log('server connection ' + (cookieString || ''));
    
        setInterval(() => socket.emit('ping', Date.now()), 1000);
    });
    
    let socketClient = undefined;
    httpServer.listen(LISTEN_PORT, 'localhost', () => {
        console.log('web server started')
    
        const options = {
            transportOptions: {
                polling: {
                    extraHeaders: {
                        'Cookie': 'hello=world'
                    }
                }
            }
        }
        socketClient = require('socket.io-client').connect('http://localhost:'+LISTEN_PORT, options);
        socketClient.on('ping', (data) => console.log('ping ' + data));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多