Socket io CORS blocked

后端 未结 2 1429
死守一世寂寞
死守一世寂寞 2021-01-27 05:53

i got this warning when using https domain and https socket io.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at htt         


        
相关标签:
2条回答
  • 2021-01-27 06:11

    use this code its work.

    app.use(
      cors({
        origin: 'http://localhost:3000', // allow to server to accept request from different origin
        methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
        credentials: true // allow session cookie from browser to pass through
      })
    );
    
    0 讨论(0)
  • 2021-01-27 06:11

    Depending on the circumstances of the project, this may not be what you need. But anyway, I write that it might help someone. I myself wanted to connect to Socket.IO + NodeJS from a script rendered with php.


    A complete working code can be like this for both ends:

    Server:

    let pth = require('path');
    let exp = require('express');
    let app = exp();
    
    //UPDATE: this is seems to be deprecated
    //let io = require('socket.io').listen(app.listen(9009));
    //New Syntax:
    let io = require('socket.io')(app.listen(9009));
    
    app.all('/', function (q, p, next) {
        p.header("Access-Control-Allow-Origin", "*");
        p.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });
    
    io.on('connection', (socket) => {
        console.log("connected");
        socket.on('msg', (msg) => {
            console.log(msg);
            io.emit('msg', msg);
        });
    });
    

    client (In my case a php script):

    <head>
        <script src="http://127.0.0.1:9009/socket.io/socket.io.js"></script>
        <script>
            let $$ = (id) => {return document.getElementById(id);};
    
            var socket = io("127.0.0.1:9009/", {
                "force new connection": true,
                "reconnectionAttempts": "Infinity", 
                "timeout": 10001, 
                "transports": ["websocket"]
            });
    
            socket.on('msg', (msg) => {$$("holder").innerHTML += msg;});
    
            let emit = (_msg) => {socket.emit("msg", _msg);};
        </script>
    </head>
    <body>
        <?php echo "php echo ...";?>
    
        <div onclick="socket.emit('msg','my msg');">BUTTON</div>
        <div id="holder">Chat ...</div>
    </body>
    
    0 讨论(0)
提交回复
热议问题