Struggling with CORS policy using socket.io nodejs

215 views Asked by At

I have found a lot of information about the CORS policy problem, but nothing worked even when I have tried every solution I found here.

My last attempt was this in the nodejs server:

var express = require('express');
var app = express();

var spawn = require('child_process').spawn;
var fs = require('fs');

app.use(express.static('public'));

const server = require('https').createServer({
    key: fs.readFileSync('/home/example/ssl/keys/c231f_0ca89_7b80bf6d84934d212df326eee9c6319f.key'),
    cert: fs.readFileSync('/home/example/ssl/certs/streaming_desytec_com_c231f_0ca89_1609334228_a73b63988075270c9f680f383b6e6a99.crt')
}, app);

var io = require('socket.io')(server);
io.set('origins', 'https://localhost:44356');

Despite my effort to solve this, I always get this error in the socket.io client:

Access to XMLHttpRequest at 'https://streaming.example.com/socket.io/?framespersecond=15&audioBitrate=22050&EIO=3&transport=polling&t=NJbfyAD' from origin 'https://localhost:44356' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I really solve this?

My website is in localhost and the nodejs server is running on a linux server remotely.

EDIT: I have this last attempt:

var cors = require('cors')

var corsOptions = {
  origin: 'https://localhost:44356',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.use(cors());
app.get('/socket.io/', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.use(express.static('public'));

it still does not work. I am wondering if that app.get call I wrote is correct, considering that the URL of the server will be:

/socket.io/?framespersecond=15&audioBitrate=22050&EIO=3&transport=polling&t=NJbfyAD

1

There are 1 answers

0
Vahid Alimohamadi On
yourapp.use(
  cors({
    origin: (origin, callback) => callback(null, true),
    credentials: true // if using cookies
  })
);

You can control it based on your environment.