我试图让一个前端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;
个字符
的数据
1条答案
按热度按时间hgqdbh6s1#
您应该使用由
http.createServer(app)
创建的server
而不是app
来侦听端口。这与TypeScript和Mongoose无关。例如:
字符串
index.html
:型
服务器端日志:
型
参见socket.io not connecting to backend with 404 error