skip to Main Content

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


  1. Chosen as BEST ANSWER

    I solved the problem.

    I added the codes to ./bin/www instead the app.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. Let app.js including same default codes and edit www to this code:

    #!/usr/bin/env node
    
    /**
     * Module dependencies.
     */
    
    var app = require('../app');
    var debug = require('debug')('server:server');
    var http = require('http');
    const socketIo = require('socket.io');
    
    /**
     * Get port from environment and store in Express.
     */
    
    var port = normalizePort(process.env.PORT || '3001');
    app.set('port', port);
    
    /**
     * Create HTTP server.
     */
    
    var server = http.createServer(app);
    const io = socketIo(server);
    /**
     * Listen on provided port, on all network interfaces.
     */
    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);
      });
    });
    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);
    
    /**
     * Normalize a port into a number, string, or false.
     */
    
    function normalizePort(val) {
      var port = parseInt(val, 10);
    
      if (isNaN(port)) {
        // named pipe
        return val;
      }
    
      if (port >= 0) {
        // port number
        return port;
      }
    
      return false;
    }
    
    /**
     * Event listener for HTTP server "error" event.
     */
    
    function onError(error) {
      if (error.syscall !== 'listen') {
        throw error;
      }
    
      var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;
    
      // handle specific listen errors with friendly messages
      switch (error.code) {
        case 'EACCES':
          console.error(bind + ' requires elevated privileges');
          process.exit(1);
          break;
        case 'EADDRINUSE':
          console.error(bind + ' is already in use');
          process.exit(1);
          break;
        default:
          throw error;
      }
    }
    
    /**
     * Event listener for HTTP server "listening" event.
     */
    
    function onListening() {
      var addr = server.address();
      var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
      debug('Listening on ' + bind);
    }
    

    Now in client side when you define socket, you have to add transports

    this.socket = io("http://localhost:3001", { transports : ['websocket'] });
    

    That worked for me


  2. You just need to update your this.socket allocation inside componentDidMount and add two options i.e. reconnectionDelayMax and reconnectionAttempts:

    componentDidMount() {
      // Connect to the Socket.io server
      this.socket = io("http://localhost:3001", {
        reconnectionDelayMax: 10000, // maximum delay between reconnection attempts
        reconnectionAttempts: 5 // number of reconnection attempts before breaking up
      });
    
      // Listen for incoming messages
      this.socket.on("chat message", (msg) => {
        this.setState((prevState) => ({
          messages: [...prevState.messages, msg],
        }));
      });
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search