简体   繁体   中英

Flask SocketIO - CORS issue

I'm trying to use Flask-SocketIO to add websocket functionality to my application.

My application architecture is heavily decoupled and as a result I want to use a different set of servers for handling the websocket stuff. However, in my testing I'm using the same server with just different ports.

When I try and connect in JavaScript with:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
    var socket = io.connect("http://dev.example.com:8000");
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I\'m connected!'});
    });
</script>

I get the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://dev.example.com:8000/socket.io/1/?t=1442224745873. (Reason: CORS request failed).

So to mitigate this, I did some CORS stuff and added the crossorigin defined here: http://flask.pocoo.org/snippets/56/

I won't post the code for the decorator as I haven't changed it from what is on the above webpage.

And then on my endpoint, I've used the decorator:

@app.route('/socket/')
@crossdomain(origin='http://dev.example.com:8000', headers='Content-Type')
def socket():
    return render_template('socket.html')

I've also tried:

@app.route('/socket/')
@crossdomain(origin='*', headers='Content-Type')
def socket():
    return render_template('socket.html')

And in the HTTP response headers of loading the /socket/ endpoint I can see the headers:

Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:HEAD, OPTIONS, GET
Access-Control-Allow-Origin:http://dev.example.com:8000
Access-Control-Max-Age:21600
Content-Length:448
Content-Type:text/html; charset=utf-8
Date:Mon, 14 Sep 2015 10:20:09 GMT
Server:Werkzeug/0.10.4 Python/2.7.9

But I still get the CORS error. Anyone got any ideas? :)

Turns out I was running the server on localhost as opposed to 0.0.0.0. Not sure why this gave me a CORS error but it resolved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM