I am trying to make a realtime chat room using reactjs and express server but I got this error:
GET http://localhost:3001/socket.io/?EIO=4&transport=polling&t=OjDsdRi 404 (Not Found)
Here are some codes of my client and server:
Here I am trying to enter show the messages to all users
Home.js
import React from "react";
import NavBar from "../Components/Navs/NavBar";
import io from "socket.io-client";
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
userName: "",
message: "",
messages: [],
};
this.inputChange = this.inputChange.bind(this);
this.enterChat = this.enterChat.bind(this);
this.sendMessage = this.sendMessage.bind(this);
}
componentDidMount() {
// Connect to the Socket.io server
this.socket = io("http://localhost:3001");
// Listen for incoming messages
this.socket.on("chat message", (msg) => {
this.setState((prevState) => ({
messages: [...prevState.messages, msg],
}));
});
}
inputChange(evt) {
this.setState({ [evt.target.name]: evt.target.value });
}
enterChat() {
// Send the user's name to the server, for example
this.socket.emit("user entered", this.state.userName);
}
sendMessage() {
// Send the user's message to the server
this.socket.emit("chat message", this.state.message);
}
render() {
return (
<>
<NavBar />
<div style={{ padding: "15px" }}>
<h3>Welcome to my chat</h3>
<p>Enter your name</p>
<input
type="text"
onChange={this.inputChange}
name="userName"
value={this.state.userName}
/>{" "}
<button onClick={this.enterChat}>Enter</button>
<div>
<h3>Chat Room</h3>
<div>
{this.state.messages.map((message, index) => (
<div key={index}>{message}</div>
))}
</div>
<input
type="text"
onChange={this.inputChange}
name="message"
value={this.state.message}
/>
<button onClick={this.sendMessage}>Send Message</button>
</div>
</div>
</>
);
}
}
I do not know if I have to add some codes to ./bin/www
file og not
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require("cors")
const http = require('http');
const socketIo = require('socket.io');
const corsOptions = {
origin: '*', // Use this for development only
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
optionsSuccessStatus: 204,
};
var indexRouter = require('./routes/index');
var message = require('./assets/js/message');
var app = express();
const server = http.createServer(app);
const io = socketIo(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors(corsOptions))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/message', message);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
// You can add custom event handlers here for chat functionality
// For example:
socket.on('chat message', (msg) => {
console.log('Message: ' + msg);
// Broadcast the message to all connected clients
io.emit('chat message', msg);
});
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I tried many ways to fix this problem, I thought first the problem because of cors but it wasn’t.
Any body knows how it can be fixed?
Thanks
2
Answers
I solved the problem.
I added the codes to
./bin/www
instead theapp.js
, it is because the old codes created a new server with no port, and when I added a port lisining it could not use same port of express server. Letapp.js
including same default codes and editwww
to this code:Now in client side when you define socket, you have to add
transports
That worked for me
You just need to update your
this.socket
allocation insidecomponentDidMount
and add two options i.e.reconnectionDelayMax
andreconnectionAttempts
: