我在 herokou.com 上运行了#NestJS 服务器,在 vercel.com 上运行了一个 React CRA 应用程序 我正在尝试将前端和后端与 websockets (socket.io) 连接起来 但是没有建立连接。在控制台中,网络请求没有显示错误,但是对应于 socket.io 超时的 GET 请求。没有回应。 nestjs网关是这样写的。 我可以看到网关的日志正在初始化。但是,即使我尝试打开客户端,也没有连接/断开连接的日志。
@WebSocketGateway()
export class AppGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
users: Record<string, any> = {};
@WebSocketServer() server;
afterInit(server: any) {
this.logger.log('Initialized');
}
handleConnection(client: any, ...args: any[]) {
console.log('connected.');
if (!this.users[client.id]) {
this.users[client.id] = client.id;
}
client.emit('yourID', client.id);
this.server.emit('allUsers', this.users);
}
在客户端我是这样连接的
socket.current = io.connect(
"https://server.herokuapp.com:" + props.port
);
我检查过 props.port 没问题。 只是在开发者工具窗口的网络请求中GET请求,超时,没有响应。 例子: https://server.herokuapp.com:43030/socket.io/?EIO=3&transport=polling&t=NAq8j0w 此 GET 不响应并超时。
最佳答案
我认为在客户端,初始化socket.io的方式是
import io from "socket.io-client";
const socket = io("http://DOMAIN:IP"); // or https
或者如果你想在 React Ref 钩子(Hook)中使用它:
const socket = useRef();
socket.currect = io("http://DOMAIN:IP"); // or https
或者我认为在一行中:const socket = useRef(io("http://DOMAIN:IP"));//或 https
关于reactjs - WebSocket SocketIO 连接无法与 Heroku 上的 NestJS 服务器一起使用,并且无法在 Vercel 上响应客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62376795/