1

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?

2
  • Are you getting 400 Bad Request in your browser console? Commented Dec 23, 2020 at 18:55
  • yes, i'm having same problem too. im getting 400 Bad Request in my browser console Commented Jan 15, 2021 at 5:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Jose Sleiter Rios, please check my answer and tell me if the solution worked for you also.
How do you even import without installing the package?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.