NestJS WebSocketGateway 未初始化

ngf*_*ixl 6 javascript websocket node.js typescript nestjs

根据 NestJS 文档,我已经实现了 websockets 网关并将其提供在AppModule. 服务器正常启动,我可以通过 http 成功提供静态资源。但我根本无法让 websockets 运行,ws 服务器不可用,ws://localhost:3333并且该afterInit函数根本没有执行。即使在我定义@SubscribeMessage.

网关实现为

@WebSocketGateway()
export class SocketGateway implements OnGatewayInit {
  afterInit() {
    console.log('Gateway initialized');
  }
}
Run Code Online (Sandbox Code Playgroud)

AppModule 正确提供网关

@Module({
  providers: [SocketGateway]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

这是引导程序的实现

export async function bootstrap() {
  let app = await NestFactory.create(AppModule);

  await app.listen(process.env.port || 3333, () => {
    console.log(`Listening at http://localhost:${port}`);
  });
}

bootstrap();
Run Code Online (Sandbox Code Playgroud)

我的依赖是

"socket.io-client": "^2.2.0",
"@nestjs/common": "5.5.0",
"@nestjs/core": "5.5.0",
"@nestjs/platform-socket.io": "^6.1.0",
"@nestjs/websockets": "^6.1.0"
Run Code Online (Sandbox Code Playgroud)

也许你直接看到了问题。感谢您的帮助,干杯!

Kim*_*ern 11

在你的项目中,nest的主要版本v5和v6是混合的。不保证不同主要版本能够正常互操作。将所有依赖项更新为 Nest v6;您可以查看迁移指南以获取有关更新的更多信息。

跑步$ npm i @nestjs/core@latest @nestjs/common@latest


当您安装新的依赖项时,请注意来自 npm 的对等依赖项警告,如下所示:

npm WARN @nestjs/websockets@6.1.0 requires a peer of @nestjs/common@^6.0.0 but none is installed.
You must install peer dependencies yourself.
Run Code Online (Sandbox Code Playgroud)