You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用ws时能否为https-proxy-agent设置自定义请求头?

使用 ws + https-proxy-agent 实现带认证/自定义头/TLS证书的WebSocket代理连接

完全理解你的需求——faye-websocket-node虽然能用,但ws是Node.js生态里最主流的WebSocket库,https-proxy-agent也是更原生、维护更活跃的代理工具组合。下面直接给你对应原示例的实现代码,每部分都精准匹配你原来的配置:

首先确保安装依赖:

npm install ws https-proxy-agent

然后是完整的实现代码:

const { WebSocket } = require('ws');
const { HttpsProxyAgent } = require('https-proxy-agent');
const fs = require('fs');

// 构造代理Agent,对应原示例的proxy配置
const proxyAgent = new HttpsProxyAgent({
  // 代理地址(支持直接传入带认证的完整URL,比如'http://username:password@proxy.example.com')
  hostname: 'proxy.example.com',
  port: 8080, // 根据代理实际端口调整,HTTPS代理通常用443
  auth: 'username:password', // 拆分认证信息更安全,避免URL日志泄露敏感内容
  // 自定义请求头,对应原示例的proxy.headers
  headers: {
    'User-Agent': 'node'
  },
  // TLS客户端证书配置,对应原示例的proxy.tls.cert
  cert: fs.readFileSync('client.crt'),
  // 如果有密钥文件,可补充:key: fs.readFileSync('client.key')
});

// 创建WebSocket客户端,传入代理Agent即可通过代理建立连接
const ws = new WebSocket('ws://www.example.com/', {
  agent: proxyAgent
});

// 可选:添加事件监听确保连接正常工作
ws.on('open', () => {
  console.log('WebSocket连接已通过代理建立');
  ws.send('Hello via proxy!');
});

ws.on('message', (data) => {
  console.log('收到消息:', data.toString());
});

ws.on('close', (code, reason) => {
  console.log(`连接关闭,代码: ${code}, 原因: ${reason.toString()}`);
});

ws.on('error', (error) => {
  console.error('WebSocket错误:', error);
});

关键配置对应说明:

  • 原示例的proxy.origin:对应HttpsProxyAgenthostname/port/auth组合,也可以直接传入带认证的完整代理URL字符串
  • 原示例的proxy.headers:直接在HttpsProxyAgent的初始化选项中配置headers即可
  • 原示例的proxy.tls.cert:在HttpsProxyAgent的选项中传入cert字段,若需密钥或CA证书,可补充keyca参数

额外提示:

  • 如果代理是HTTP协议而非HTTPS,记得改用HttpProxyAgent(同样从https-proxy-agent包中导入)
  • 测试环境下若需跳过代理证书验证,可在TLS选项中添加rejectUnauthorized: false(生产环境不建议)

内容的提问来源于stack exchange,提问作者Aero Wang

火山引擎 最新活动