Asking
Asking

Reputation: 4200

Use websockets in NestJs and ReactJS

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?

Upvotes: 1

Views: 4013

Answers (1)

Asking
Asking

Reputation: 4200

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.

Upvotes: 1

Related Questions