5

I have this in server.js

//socket io config
const server = require('http').createServer(app)
const io = require('socket.io')(server)
io.on('connection', function (socket) {
  socket.on('SOCKET_COMMENT_RECEIVED', ({ notification }) => {
    io.emit(`SOCKET_COMMENT_RECEIVED`, notification)
  })
  //and many more
})

In my client (react)

import io from 'socket.io-client'
const socket = io('localhost:3001') // working in localhost

in my prod I do this checking

let socket = io('localhost:3001')
if(process.env.NODE_ENV === 'production') { socket = 
  io('https://api.example.com:3001') 
}

Why is it so? I don't think it's cors issue because I already did

app.use(cors({
  origin: true,
  credentials: true
}))

my package.json deps

"socket.io": "^2.1.1",
"socket.io-client": "^2.1.1",
Alisa T Morgan
  • 667
  • 1
  • 7
  • 12

2 Answers2

0

In your server code please add the following line

io.set('origins', '*:*');

So your code will be

  //socket io config
  const server = require('http').createServer(app)
  const io = require('socket.io')(server)
  io.set('origins', '*:*');
  io.on('connection', function (socket) {
    socket.on('SOCKET_COMMENT_RECEIVED', ({ notification }) => {
      io.emit(`SOCKET_COMMENT_RECEIVED`, notification)
    })
    //and many more
  })

For more help to follow this tutorial & this question.

The source code is available here.

Hope this will help you !!

Santosh Shinde
  • 6,045
  • 7
  • 44
  • 68
0

To know which route you should point in the api, access to the address "/socket.io/". For example, if you are runing on localhost:3001 should be "http://localhost:3001/socket.io/" and the response

{"code":0,"message":"Transport unknown"}

Be sure you are declaring the same server name and route in production. If you use a kind of proxy or sub route like /api you have to add it. This is an example.

SERVER ROUTE DECLARATION

const httpServer = require("http").createServer(app);
const options = {
    path: "/api/socket.io",
    cors: {
        origin: "*"
    }
};
const io = require("socket.io")(httpServer, options);

io.on('connect', function (socket) {
    socket.on('SOCKET_COMMENT_RECEIVED', ({ notification }) => {
        io.emit(`SOCKET_COMMENT_RECEIVED`, notification)
    })
});

CLIENT DECLARATION LISTENER (FOR REACT HOOKS)

  let socket = io("https://www.yoursite.com", { path: '/api/socket.io/' });

  React.useEffect(() => {
    socket.on('SOCKET_COMMENT_RECEIVED', function (data) {
      console.log(`RECEIVED`);
    });
    return () => {
      socket.disconnect();
    }
  }, []);
Lalo19
  • 67
  • 3