skip to Main Content

All versions installed of socket.io and socket.io-client are the same in my mern app.

Here is my server code:

const app = express();

mongoose.connect(MONGOOSE_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
}).then(() => {
  console.log(`MongoDB connected successfully`);
}).catch((error) => console.log(`${error} did not connect`));

const server = http.createServer(app);

const io = new Server(server,  console.log('io is being called'));


io.on('connection', (socket) => {
  console.log(socket.id)
})

server.listen(3005, () => {
  console.log(`Server is listening on PORT 3005`);
});

here is my client code:

import io from 'socket.io-client';

const socket = io('http://localhost:3005'); 
socket.on('connect', () => {
    console.log('you connected!')
})

Why doesn’t it show the socket io connection was made when I npm start both my client and server?

On my server side, it console logs that:

  1. io is being called,
  2. Server is listening on PORT 3005,
  3. MongoDB connected successfully

Does anyone know if I’m missing anything?

3

Answers


  1. Chosen as BEST ANSWER

    The reason it wasn't being made was because my socket.io-client code was placed in an individual js file.

    In order for it to run, it needs to be in a component on the client side rendered in App.js.

    Once I did that, the connection was made between server and client.


  2. try it

    const express = require('express')
    const app = express()
    const http = require('http');
    const socket = require('socket.io');
    const cors = require('cors');
    const server = http.createServer(app);
    
    
    app.use(cors({
        origin: ['http://localhost:3000'],
        credentials: true
    }))
    
    const io = socket(server, {
        cors: {
            origin: '*',
            credentials: true
        }
    })
    
    io.on('connection', (socket) => {
      console.log(socket.id)
    })
    
    Login or Signup to reply.
    1. There is no issue in your code. console.log('you connected!') will NOT show up in server side logs because it is client side code.

    2. You have to check the client side logs in the browser you are using to open the client in order to view you connected!. The shortcut to Dev Tools is F-12 in Google Chrome for example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search