I have a server that also establishes socket.io server.
I am running docker-compose up
both server and client comes up and server works in 0.0.0.0:8000
and client in 0.0.0.0:3000
but the socket connection is not working.
The ports on running backend looks with docker ps
as 0.0.0.0:8000-8001->8000-8001/tcp
.
I get error from app in the console:
Access to XMLHttpRequest at 'http://0.0.0.0:8001/socket.io/?
EIO=4&transport=polling&t=NiQWpj0' from origin 'http://<IP-WHERE-APP-RUNNING>:3000' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Running this in local computer without containers it works.
Any suggestions on how to solve this?
server.js
var express = require('express');
var app = express();
var multer = require('multer')
var cors = require('cors');
var path = require('path');
// Setup socket connection with clien
const io = require('socket.io')(8001, {
cors: {
origin: '*',
}
});
const sockets = {}
var socketInstance = null
io.on("connection", socket => {
socket.on("connectInit", function() {
// The socket ID is stored
sockets[socket.id] = socket
socketInstance = socket
socket.on('disconnect', function() {
delete sockets[socket.id];
});
// The sockets object is stored in Express so it can be grabbed in a route
app.set("sockets", sockets)
})
});
// The io instance is set in Express so it can be grabbed in a route
app.set("io", io)
app.use(cors())
...
...
And in client:
import io from 'socket.io-client';
// Set up socket connection with server
const socket = io('ws://0.0.0.0:8001', { // localhost:8001 in case running locally
'sync disconnect on unload': true,
});
socket.emit('connectInit');
export default socket;
Update:
I have now tried with:
// Setup socket connection with clien
const io = require('socket.io')(8001, {
cors: {
origin: 'http://<IP-WHERE-APP-RUNNING>:3000',
}
});
As suggested in https://socket.io/docs/v4/handling-cors/ but with no avail