0

I'm getting CORS error in server but I'm not getting this error in local. My project is working in local but when I try to connect my socket.io api in server I'm getting this error in console:

Access to XMLHttpRequest at 'https://my-web-site.com.tr/socket.io/?EIO=4&transport=polling&t=ORwXVX_' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My api code is like this:

const cors = require('cors');
const express = require('express');
const app = express();
const http = require('http').Server(app);

const port = process.env.PORT || 3200;

app.use(cors({
    origin: '*'
}));

const io = require('socket.io')(http, {
    cors: {
        origin: '*',
        methods: ["GET", "POST"],
        allowedHeaders: ["*"],
        credentials: true
    }
}).of('/abcHub');

io.on('connection', (socket) => {
    console.log("Connected: " + socket.id);

    socket.on('disconnect', () => {
        console.log(`Disconnect ${socket.id}`);
        
    });
});


const server = http.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

My client code like this:

   <script src="node_modules/jquery/dist/jquery.min.js"></script>
   <script src = "node_modules/socket.io/client-dist/socket.io.min.js"></script>
   <script>
  
      $(document).ready(() => {
      const socket = io("https://my-web-site.com.tr/abcHub"); 

      });
   </script>

I wonder that why I don't get cors error in local but I get in server? If you have any question, you can ask. Thanks.

fatih
  • 149
  • 1
  • 1
  • 12

2 Answers2

1

I solved. The problem is that iis is not hosting node.js project without redirection. I upload iisnode to server and did redirection settings. Then project worked. Thanks.

fatih
  • 149
  • 1
  • 1
  • 12
0

Try this:

const express = require("express")
const app = express()
const http = require("http")
const cors = require("cors")
const { Server } = require("socket.io") 
const corsOptions = require("./config/corsOptions.js")

app.use(cors())
const server = http.createServer(app)

const port = process.env.PORT || 3001

const io = new Server(server , corsOptions )

server.listen(port,() => {
    console.log("server listening on ","3001")
})

where the corsOptions is

const corsOptions = {
    cors: {
        origin: "*"
    }
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31