nestjs + socket.io将WebSockets从嵌套路径的微服务中提供,而不是从主机根目录中提供,始终返回404 Not Found。

7

我正在使用nestjs实现的socket.io。我的生产架构依赖于负载均衡器,用于将路径上的请求路由到微服务容器。

其中一个包含websocket,并与用户数据交互,嵌套在mydomain.com/apis/user 上。

在我的网关上,我已配置它使用此路径:

@WebSocketGateway({ path: "/apis/user/gateway", namespace: "/apis/user/gateway" })

我尝试过没有命名空间和只有路径的变化。

我还有一个全局前缀:app.setGlobalPrefix("apis/user");去掉它没有任何区别,似乎无论有没有前缀,我都需要定义到网关的路径。

然后在客户端,我试图通过在URL中添加路径或在选项对象中连接到它,如下所示:

    const endpoint = "https://example.com/apis/user/gateway";

    socket = io(endpoint, {
      secure: true,
      path: "/apis/user/gateway",
    });

这适用于网关中路径和handleConnection触发器,但在后台配置轮询却无效,客户端仍会抛出以下错误:
 https://example.com/apis/user/gateway/?EIO=4&transport=polling&t=NXVpMfB 404 Not Found

我有同样的问题。只有根目录 / 下的默认配置起作用 :( - chrismarx
1个回答

3

我遇到了同样的问题,所有不同的选项让我感到困惑。但我最终解决了这个问题,以下是有效的做法:

对于nestjs:

@WebSocketGateway({
  cors: {
    origin: '*',
  },
  namespace: '/api/v1/ws',
  path: '/api/v1/ws/socket.io',
})

对于socket.io:

const newSocket = io("http://localhost:3000/api/v1/ws", {
      path: "/api/v1/ws/socket.io",
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接