0

I have this simple nodejs websocket program running in an EC2 instance

const app = require("express")();
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
var cors = require('cors');
app.use(cors());
io.on("connection", socket => {
console.log("new client connected");
});

httpServer.listen(3000, () => console.log('Server running on port 3000'));

As you can see I am using CORS in my program but When i am connecting from browser i am getting this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ec2-XXXXXX.compute.amazonaws.com:3000/socket.io/?EIO=3&transport=polling&t=NcZV0e-. (Reason: CORS request did not succeed).

THis is how i am calling it from browser:

<script type="text/javascript">
    var socket = io.connect('https://ec2-XXX.compute.amazonaws.com:3000');
        socket.on('connect', (s) => {
        console.log('connected!');
    });

    </script>
Manish Kumar
  • 10,214
  • 25
  • 77
  • 147
  • Have to try to use cors middleware before initializing the socket.io with http server ? – Ameer Hamza May 25 '21 at 12:38
  • Above NODEJS program is all i am trying in my EC2 – Manish Kumar May 25 '21 at 12:40
  • Try to use app.use(cors()) beofore socket intilization ` const app = require("express")(); const httpServer = require("http").createServer(app); var cors = require('cors'); app.use(cors()); const io = require("socket.io")(httpServer); io.on("connection", socket => { console.log("new client connected"); }); httpServer.listen(3000, () => console.log('Server running on port 3000')); ` – Ameer Hamza May 25 '21 at 12:44
  • still same issue – Manish Kumar May 25 '21 at 12:51
  • So, I think this issue not with nodejs but with the ec2 instance. Has you allowed incoming and outgoing traffic in security group of ec2 ? – Ameer Hamza May 25 '21 at 13:06
  • Have you checked this [link](https://stackoverflow.com/questions/24058157/socket-io-node-js-cross-origin-request-blocked) ? – Đăng Khoa Đinh May 25 '21 at 17:56

0 Answers0