const Home = () => {
const [msg, setMsg] = useState('')
const socket = io.connect('http://localhost:5000', { autoConnect: true })
function enterSendMsg(e){
setMsg(e.target.value)
document.addEventListener('keydown', (event) =>{
if(event.key == "Enter"){
socket.emit('send msg', msg)
setMsg('')
}
})
}
return (
<div>
<Navbar />
<div className="chatArea">
<ul className="messages"></ul>
</div>
<div></div>
<MyInput
value={msg}
placeholder='Пиши сюда'
type='text'
onChange={(e)=> enterSendMsg(e) }
/>
</div>
)
}
export default Home
Вот какой код в React.
require('dotenv').config()
const express = require('express')
const app = express()
const server = require('http').createServer(app)
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:3000",
}})
const PORT = process.env.PORT || 6000
app.use(express.json())
io.sockets.on('connection', function(socket){
socket.on('send msg', function(data){
console.log(data)
})
})
const start = async ()=>{
try {
server.listen(PORT, ()=> console.log(`Server on ${PORT}`))
} catch (e) {
console.log(e)
}
}
start()
Вот код из сервера.
При вводе Dima и нажатии Enter в консоле должно вывести Dima, но выводет вот это: