React hooks,typescript,mongoose,express和socket.io一起工作

yzuktlbb  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(134)

我试图让一个前端React应用程序与socket.io连接到NodeJS express API

import React, { useEffect, useState } from "react";
import io from "socket.io-client";

const socket = io("http://localhost:4000");

const Chat: React.FC = () => {
  const [messages, setMessages] = useState<string[]>([]);
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    // Evento para recibir mensajes del servidor
    socket.on("chat message", (msg: string) => {
      setMessages((prevMessages) => [...prevMessages, msg]);
    });

    return () => {
      // Limpia el evento al desmontar el componente
      socket.off("chat message");
    };
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    socket.emit("chat message", inputValue);
    setInputValue("");
  };

  return (
    <div>
      <h1>Walkie Talkie Chat</h1>
      <ul>
        {messages.map((message, index) => (
          <li key={index}>{message}</li>
        ))}
        <li>final</li>
      </ul>
      <form onSubmit={handleSubmit}>
        <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default Chat;

个字符


的数据

hgqdbh6s

hgqdbh6s1#

  • ”socket.io“:“^4.7.1”*

您应该使用由http.createServer(app)创建的server而不是app来侦听端口。这与TypeScript和Mongoose无关。
例如:

import cors from 'cors';
import express from 'express';
import http from 'http';
import socketio from 'socket.io';

const app = express();
app.use(express.json());
app.use(cors());

const PORT = 4000;
app.set('port', PORT);

const server = http.createServer(app);
const io = new socketio.Server(server);

io.on('connection', (socket: socketio.Socket) => {
    console.log('Nuevo cliente conectado');
    socket.on('chat message', (msg: string) => {
        console.log('Mensaje recibido: ' + msg);
        io.emit('chat message', msg);
    });
    socket.on('disconnect', () => {
        console.log('Cliente desconectado');
    });
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.get('*', (_, res) => {
    res.status(404).send('Nothing here');
});

server.listen(PORT, () => {
    console.log(`Servidor iniciado en el puerto ${PORT}`);
});

字符串
index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0"
        />
        <title>Document</title>
    </head>
    <body>
        <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
        <script>
            var socket = io('http://localhost:4000');
            socket.emit('chat message', 'ok');
        </script>
    </body>
</html>


服务器端日志:

Servidor iniciado en el puerto 4000
Nuevo cliente conectado
Mensaje recibido: ok


参见socket.io not connecting to backend with 404 error

相关问题