【问题标题】:Use websockets in NestJs and ReactJS在 NestJs 和 ReactJS 中使用 websocket
【发布时间】:2021-03-24 22:25:06
【问题描述】:

我想通过 NestJs 使用 websocket。根据我创建的文档:

// 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;

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

export class TestModule {
    
}

现在,我使用 react js 尝试从 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() 时,代码不起作用并且我在服务器上没有得到任何东西,为什么以及如何使代码起作用?

【问题讨论】:

  • 您的浏览器控制台中是否收到 400 Bad Request?
  • 是的,我也遇到了同样的问题。我在浏览器控制台中收到 400 Bad Request

标签: javascript reactjs websocket nestjs


【解决方案1】:

在我的情况下,下一个解决方案是:

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

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

【讨论】:

  • @Jose Sleiter Rios,请检查我的回答并告诉我该解决方案是否也适用于您。
  • 不安装包怎么导入?
猜你喜欢
  • 2022-08-12
  • 2021-06-12
  • 2017-09-13
  • 1970-01-01
  • 2022-11-24
  • 2023-03-06
  • 2020-09-17
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多