I chat using React, react-router, expressjs and socket.io. There was a problem during the chat. There is a form and a message input field in it. When you press enter, the message is sent to the server normally, but the client's on () method, which is triggered when a message arrives from the server, displays the messages in a strange way. That is, if you send the first message to the server, it is displayed normally, but if you send the second message to the server, then two identical messages come in the reply, that is, with each sent message, one more message comes back from the server (see screenshot .). Client code (React component):
import React, { Component } from 'react' export default class Chat extends Component { addMessage (e) { e.preventDefault(); window.socket.emit('chat message', e.target.message.value); e.target.message.value = ''; window.socket.on('chat message', function(msg){ document.getElementById('chatMsgList').innerHTML += '<li>' + msg + '</li>'; }); } render() { return ( <div> <ul id="chatMsgList"></ul> <form id="chatForm" onSubmit={this.addMessage}> <input autoComplete="off" type="text" id="chatInp" name="message" className="form-control"/> </form> </div> ) } And another problem with the same chat. If you open a chat in two browsers and write messages, they will not appear in another window until something is sent out of the window that opens, only then if you write something again in the first window, it will already come in the second. In general, it is also strange somehow. Either I did something wrong on the server, or some kind of problem on the client side, that is, in React Code on the server:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); (function initWebpack() { var express = require('express'); const webpack = require('webpack'); const webpackConfig = require('./webpack/common.config'); const compiler = webpack(webpackConfig); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath, })); app.use(require('webpack-hot-middleware')(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000, })); app.use(express.static(__dirname + '/')); })(); app.get(/.*/, function root(req, res) { res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function() { console.log('Server on 3000 listening'); }); code index.html:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="public/styles/common.css"> </script> <title>React app</title> </head> <body> <div id="root"></div> <script src="/socket.io/socket.io.js"></script> <script src="/dist/bundle.js"></script> <script> window.socket = io(); </script> </body> </html> I hope for your help in making chat work
