在 NestJs 和 ReactJS 中使用 websockets [英] Use websockets in NestJs and ReactJS

查看:66
本文介绍了在 NestJs 和 ReactJS 中使用 websockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

之后我在我的module中连接了上面的代码;

After that i connected the code above in my module;

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

export class TestModule {
    
}

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

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;

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

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?

推荐答案

就我而言,下一个解决方案是:

In my case the solution is next:

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

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

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

这篇关于在 NestJs 和 ReactJS 中使用 websockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆