reactjs - WebSocket SocketIO 连接不适用于 Heroku 上的 NestJS 服务器并在 Vercel 上响应客户端
问题描述
我有在 herokou.com 上运行的#NestJS 服务器和在 vercel.com 上运行的 react CRA 应用程序我正在尝试使用 websockets (socket.io) 连接前端和后端但是没有建立连接。在控制台中,网络请求没有显示错误,但 GET 请求对应于 socket.io 超时。没有回应。这就是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
或者如果你想在一个反应 Ref 挂钩中使用它:
const socket = useRef();
socket.currect = io("http://DOMAIN:IP"); // or https
或者在一行中我认为:const socket = useRef(io("http://DOMAIN:IP")); // or https
推荐阅读
- javascript - Firestore如何停止Transaction?
- gstreamer - GStreamer 预录
- java - org.springframework.web.bind.MissingServletRequestParameterException,tomcat 无法获取日期
- java - 将 HEX 颜色转换为 BitmapDescriptorFactory.defaultMarker 方法的浮点颜色
- php - 当从 phpunit 调用时,laravel 中的 $request->all() 返回空
- angular - Angular dart - 选择对象作为模型(不是字符串)
- android - 我的测试版应用程序上没有兼容的设备
- node.js - 温斯顿每日轮换删除 .GZIP 文件
- angularjs - 调试第三方 AngularJS 代码
- php - 在php中使用月份名称和年份对数组进行排序