1

我想通过 NestJs 使用 websockets。根据我创建的文档:

// events.gateway.ts
import {
    MessageBody,
    OnGatewayInit,
    SubscribeMessage,
    WebSocketGateway
} from "@nestjs/websockets";

@WebSocketGateway(81, { transports: ['websocket'] })

export class EventsGateway implements OnGatewayInit {
    @SubscribeMessage('events')

    handleEvent(@MessageBody() data: string): string {
        console.log(data, 'socket')
        return data;
    }

    afterInit(server: any): any {
        console.log('init')
    }
}

之后,我将上面的代码连接到我的module;

@Module({
    providers:[TestService, EventsGateway],  // connect EventsGateway
    controllers:[TestController],
})

export class TestModule {
    
}

现在,使用 react js 我尝试从 ui 发送消息:

import React, {} from 'react';
import './App.css';
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:81/test";


function App() {
  const socket = socketIOClient(ENDPOINT, {
    transports: ['websocket']
  });


  function sendEmail(e: any) {
    e.preventDefault(); 
    socket.emit('events', {
      name: 'Nest'
    });
  }


  return (...);
}

export default App;

问题:现在当我触发时socket.emit(),代码不起作用并且我在服务器上没有得到任何东西,为什么以及如何使代码可用?

4

1 回答 1

1

在我的情况下,解决方案是下一个:

  1. 我没有使用 npm 包,但我简单地添加了<script src="/socket.io/socket.io.js"></script>
  2. 添加import { io } from 'socket.io-client';

该解决方案对我有用,但我不明白为什么 npm 包不起作用。

于 2021-01-15T07:44:49.520 回答