0

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

eemilk
  • 1,375
  • 13
  • 17

1 Answers1

0

In my specific case the answer was to put <IP-WHERE-APP-RUNNING> in palce of 0.0.0.0. The ip is a remote vm where these containers are running. I could have been more clear but the server and app both run in same VM.

I'm still running the react app in development server, so I don't know how things will go from here onward.

What helped me were answer and using curl:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

curl command I used:

curl -H "Origin: <IP-WHERE-CONTAINERS-RUN>:3000" --verbose \
  <IP-WHERE-CONTAINERS-RUN>:8000

Here I am looking to get the CORS options as response.

In the future it seems I need to use a reverse proxy as suggested here in the accepted answer:

Access Control Origin Header error using Axios in React Web throwing error in Chrome

eemilk
  • 1,375
  • 13
  • 17