问题
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:
- I didn't use the npm package but i simple added
<script src="/socket.io/socket.io.js"></script>
- 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