Socket io CORS blocked

后端 未结 2 1450
死守一世寂寞
死守一世寂寞 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

    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):

    
        
        
    
    
        
    
        
    BUTTON
    Chat ...

提交回复
热议问题