首页 > 解决方案 > 使用 https 时未建立套接字连接

问题描述

我正在尝试与反应前端建立套接字连接。当我使用 http API 进行连接时,它工作得很好,但是当我尝试将其与 https 服务器连接时,我得到了连接失败的错误。

这是我要连接的反应代码:

import io from "socket.io-client";


const CONNECTION_PORT = 'https://socket.abcd.com/api'         // (I did reverse proxy in nginx for /api endpoint) which is not connecting. I also have SSL certificate purchased for this API. Whereas,

const CONNECTION_PORT = 'http://localhost:5000'.    // this works perfectly fine.

useEffect(() => {
    socket = io(CONNECTION_PORT, {
      transports: ["websocket"],
    });
  });

有没有人面临同样的问题?请让我知道可以解决此问题的方法。

标签: node.jsreactjssocket.io

解决方案


这完全取决于您定义代理的方式(nginx)

你听从了这些建议吗?

https://socket.io/docs/v3/reverse-proxy/#NginX

/etc/nginx/nginx.conf的内容:

http {
  server {
    listen 80;
    server_name example.com;

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;

      proxy_pass http://localhost:3000;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
  }
}

推荐阅读