Use websockets in NestJs and ReactJS

若如初见. 提交于 2021-01-28 05:07:44

问题


I want to use websockets using NestJs. According to the documentation i created:

// 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')
    }
}

After that i connected the code above in my module;

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

export class TestModule {
    
}

And now, using react js i try to send messages from 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;

Question: Now when i trigger socket.emit(), the code does not work and i don't get anything on the server, why and how to make the code workable?


回答1:


In my case the solution is next:

  1. I didn't use the npm package but i simple added <script src="/socket.io/socket.io.js"></script>
  2. Add import { io } from 'socket.io-client';

The solution worked for me, but i don't understand why npm package doesn't work.



来源:https://stackoverflow.com/questions/65286333/use-websockets-in-nestjs-and-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!