I makes a project where wants to use a socket.io.
Now I have an error in browser console:
Access to XMLHttpRequest at ‘https://back.escootrent.com/socket.io/?EIO=4&transport=polling&t=OwxDnkM’ from origin ‘https://www.escootrent.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
How you can see I use my sub-domains, with which averything brokes. Awary domain links with their directory.
Client directory is tha basic web application on html, css, js, php. And now to connect with server using io('https://back.escootrent.com/socket.io');
The other directory is server for socket.io with this code:
server.js
const express = require('express');
const https = require('https');
const fs = require('fs');
const app = express();
const options = {
key: fs.readFileSync('./_.escootrent.com_private_key.key'),
cert: fs.readFileSync('./escootrent.com_ssl_certificate.cer')
};
const server = https.createServer(options, app);
const io = require('socket.io')(server);
app.get('/chats', function(req, res) {
res.send('answ');
});
io.on('connection', socket => {
console.log('User connected', socket.id);
})
io.on('disconnect', () => {
console.log('User disconnected', socket.id);
});
server.listen(443, (err) => {
if (err) {
throw Error(err);
}
console.log('Server started!');
});
All this based on OpenServer and works with local parametrs, but don`t work with domains.
I tried this and nothing changed
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'https://www.escootrent.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
io.origins((origin, callback) => {
if (origin === 'https://www.escootrent.com') {
callback(null, true);
} else {
callback('Origin not allowed', false);
}
});
const cors = require('cors');
app.use(cors());
2
Answers
In my situation, solution is in using different port:
And open this port in the setings of youe firewall.
As per doc
io.origins
is depreciated, so remove thisChange the initialisation to
Full code