所以我打算使用socket.io基于websockets构建react / node聊天应用程序。当我在工作时,我开始遇到非常奇怪的错误,长话短说,当我尝试从前端反应服务器向后端节点服务器发出“消息”事件时,它只能工作6次。我试图多次重构代码,更改socket.io的各种配置和预设,但最后这个问题仍然保持不变。这是实际的代码:
如果有人遇到过类似的错误,并且有解决方案,我会很高兴听到它,因为我花了大量时间浏览有关socket.io的其他论坛上的堆栈溢出和线程
反应:
import React, { Component } from 'react';
import classes from './Chat.module.scss';
import axios from 'axios';
import openSocket from 'socket.io-client';
class Chat extends Component {
state = {
messages: [],
message: ''
};
componentDidMount() {
const io = openSocket('http://localhost:8080');
io.on('message', data => {
console.log(data);
});
}
messageChanged = e => {
this.setState({ message: e.target.value });
};
messageSent = () => {
axios.post('http://localhost:8080/message', {
message: this.state.message
});
};
render() {
return (
<div className={classes.wrapper}>
<p>Hello</p>
<div />
<input
type="text"
onChange={this.messageChanged}
value={this.state.message}
/>
<button onClick={this.messageSent}>Send</button>
</div>
);
}
}
export default Chat;
根节点文件:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const filemanagerMiddleware = require('@opuscapita/filemanager-server')
.middleware;
const cors = require('cors');
const path = require('path');
const socketIo = require('socket.io');
const config = {
fsRoot: path.join(__dirname, 'public', 'files'),
rootName: 'root',
logger: {
log: () => {},
info: () => {},
warn: () => {},
error: () => {}
}
};
const router = require('./router');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const port = process.env.PORT || 8080;
const server = app.listen(port);
const io = socketIo.listen(server);
app.use((req, res, next) => {
req.io = io;
next();
});
app.use('/', router);
io.sockets.on('connection', socket => {
console.log('User connected');
});
io.sockets.on('message', data => {
console.log(data);
});
app.use('/filemanager', filemanagerMiddleware(config));
(async () => {
await mongoose.connect('mongodb://localhost:27017/practice-app', {
useNewUrlParser: true
});
console.log(\Connected to DB and listening on ${port}...`);})();
分离的路由器文件,其中包含所有控制器:
const chatController = require('./controllers/chat');
const router = require('express').Router();
router.post('/signup', authenticationController.signup);
router.post('/signin', authenticationController.signin);
// this is the route for posting data which is then emitted through websocket
router.post('/message', chatController.sendMessage);
module.exports = router;
分离的聊天控制器文件:
exports.sendMessage = (req, res) => {
const { message } = req.body;
req.io.sockets.emit('message', { message });
};
请注意,req.io是通过中间件传递的socket.io服务器的实例