node.js - Nodejs + Socket.io + Nginx 反向代理不工作

标签 node.js nginx socket.io

我正在为 NodeJS 应用程序设置 Nginx 反向代理,该应用程序在托管其他 NodeJs 应用程序的服务器上包含 Socket.IO。

NodeJS 通过端口 3001 上的 PM2 运行。这是 Nginx 配置:

server {
        listen 80;
        server_name iptv-staging.northpoint.org;
        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;

                proxy_pass http://localhost:3001;

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

当直接通过服务器的 IP 地址运行应用程序时 http://xxx.xxx.xxx.xxx:3001/ 一切正常运行。来自 Socket.IO 的 Ping/Pong 请求大约为 50 毫秒(默认 pingTimeout 为 5000 毫秒)。通过 DNS 名称 http://iptv-staging.northpoint.org 访问应用程序时,客户端报告 ping 超时并断开连接。它会在第一次尝试时重新连接,然后在第一次 ping/pong 请求时再次断开连接。

据我所知,问题必须与 Ngnix 反向代理以及 websockets 的路由方式有关。似乎是服务器对 ping 请求的回复没有到达客户端。但我似乎无法确定原因。非常感谢任何帮助。

最佳答案

我遇到了完全相同的问题。一个工作人员提供了答案,老实说我并不完全理解,所以我没有功劳,但我希望我能从我的代码中梳理出答案。

首先,您需要通过添加 X-Real-URI header 告诉 nginx 发送客户端看到的传入 URI:

proxy_set_header X-Real-URI $request_uri;

此路径与最终在您的服务器中看到的路径之间的差异告诉您 URI 的基本路径。

然后,我在返回 URI 信息的服务器上创建了一个 API 端点。这是告诉客户端使用哪个地址进行连接的关键。

apiRoutes.get('/options', (req, res) => {

  Log.info('Received request for app options.');

  // This isn't applicable to you, just showing where options declared.
  let options = JSON.parse(JSON.stringify(config.get('healthcheck.options')));

  // Decide what port to use.  It might be a port for a dev instance or from Env
  if ((process.env.PORT !== options.port) && (process.env.PORT > 0)) {
    options.port = process.env.PORT;
  }

  // This is the important bit...
  var internalUri = req.originalUrl;
  var externalUri = req.get('X-Real-URI') || internalUri;
  options.basePath = externalUri.substr(0, externalUri.length - internalUri.length + 1);

  res.status(200).send(JSON.stringify(options));
});

我的客户端是一个 React 应用程序,您可能会考虑需要如何实现,但我是这样做的。

这是我调用选项服务的“助手”函数...

export async function getOptions() {

  const res = await axios.get('/api/options');

  return res.data;

}

在我的 React 页面中,我会在页面加载时调用它...

componentDidMount() {

    getOptions()
        .then((res) => {
            this.setState({ port: res.port });

        // Call a client-side function to build URL.  Incl later.
        const socketUrl = getSocketUrl(res.port);

        console.log(`Attempting to connect to sockets at ${socketUrl}.`);

        // This is where it all comes together...
        const socket = io(socketUrl, { path: `${res.basePath}socket.io` });
        socket.on('connect', function () { console.log(`Connected to ${socketUrl}`); });

        socket.on('message', (result) => {
          console.log(result);
        });

        socket.on('data', (result) => {
          console.log(`Receiving next batch of results.`);

          const filteredResults = JSON.parse(result));

          // Do something with the results here...

        });

    });

.....

最后,getSocketUrl 函数...

function getSocketUrl(port) {

  console.log(`${window.location.hostname}`);

  if (window.location.hostname.toString().includes('local')) {
    return `localhost:${port}`;
  }

  return `${window.location.hostname}`;

}

关于node.js - Nodejs + Socket.io + Nginx 反向代理不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56065076/

相关文章:

tomcat8 - 400 的自定义错误页面

if-statement - 仅当 cookie 存在时,如何有条件地覆盖 nginx 中的 header ?

javascript - Babel-node 不会在预设环境中转换扩展运算符

javascript - Mongoose 在对象数组中查找值

django - 多个带有 nginx proxy_pass 的 django 应用程序并重写

node.js - 如何从一个socket.io Node 应用程序向另一个socket.io Node 应用程序发送消息

javascript - 有没有在 node.js 中做实时模型的框架?

javascript - 如何为浏览器客户端设置 RabbitMQ 绑定(bind)?

javascript - Node.js mysql - 嵌套查询和异步/等待

javascript - 如何访问函数中的命名参数?