1

I have a question about the socket. Server side with the address http://node.elyjm.ir I wrote the following code (in the index.js file)

var mysql = require("mysql");
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
app.get('/', function(req, res){
res.send('connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
console.log('a client connected');
});

and in client side:

<!DOCTYPE html>
<html>
<head>
  <title>Socket.IO chat</title>
</head>
<body>
<div id="display"> </div>
 <div id="socketio"> </div>
  <script src="socket.io.js"></script>
  <script>
    var socket = io("http://node.elyjm.ir:3000/");
    function myFunc() {
        var socket = io();
    socket.on('connect', function () {
      document.getElementById("socketio").innerHTML = "socket connected2222";
    });
    }
  </script>

  <?php
    echo '<script> myFunc(); </script>';
  ?>
  
</body>

</html>

But I see the client side error below

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://node.elyjm.ir:3000/socket.io/?EIO=4&transport=polling&t=NyTVkVU. (Reason: CORS request did not succeed). Status code: (null).

  • Does this answer your question? [Socket.io + Node.js Cross-Origin Request Blocked](https://stackoverflow.com/questions/24058157/socket-io-node-js-cross-origin-request-blocked) Not running both on `localhost`. See `origin` - same origin policy. – ficuscr Feb 22 '22 at 08:22

1 Answers1

0

Don't re declare socket in myFunc

var socket = io("http://node.elyjm.ir:3000/");
    function myFunc() {
        // var socket = io();  // ################ delete / comment this ################
    socket.on('connect', function () {
      document.getElementById("socketio").innerHTML = "socket connected2222";
    });
    }

Rahmat Fathoni
  • 1,272
  • 1
  • 2
  • 8