首页 > 解决方案 > 代理后面的socket.io客户端在浏览器中工作正常,而不是在nodejs应用程序中

问题描述

我被 Socket.io 交换所困。如果 javascript 代码托管在浏览器 (Chrome/Firefox) 中,则连接在中间使用或不使用代理。

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>

<script>
    var socket = io('https://uri', { secure: true, reconnect: true, rejectUnauthorized: false });
    socket.on('connect', function () {
        console.log('Connected to server!');
        socket.emit('register', 'ClientName');
    });
</script>

相反,相同的代码在 nodejs 上运行,使用 node v10.4.0 和模块 "socket.io": "^2.1.1" 仅在连接是直接的情况下才有效。

我尝试使用 socket.io-proxy(很旧),但它似乎与 socket.io-client 不一致,并且它不起作用,或者我遗漏了一些东西。

很明显,“浏览器中的脚本”可以访问代理设置/通道......无论如何,或者节点运行时不知道的其他一些设置。

感谢您的任何建议。

洛伦佐

标签: node.jsproxysocket.io

解决方案


Did you manage to solve the problem? If you are behind a simple http(s) proxy you can try with the https-proxy-agent package..

 var HttpsProxyAgent = require('https-proxy-agent');
 let p = 'http://my.proxy.address:8080';
 let agent = new HttpsProxyAgent(p);

 let opts = {
               secure: true,
               rejectUnauthorized: false,
               reconnect: true,
               agent: agent
            };

 let socket = require('socket.io-client').connect('https://my.socket.io.server', opts);

推荐阅读