4

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
  • 617
  • 1
  • 7
  • 12

1 Answers1

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
  • 5,797
  • 6
  • 44
  • 63