Flask-socketio - failed to set “Access-Control-Allow-Origin” response header

寵の児 提交于 2020-08-10 01:15:46

问题


I wrote this simple flask-socketio code:

from flask import Flask
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'

socketio = SocketIO(app)


@socketio.on('message')
def handle_message(msg):
    print 'Message:' + msg
    send(msg, broadcast=True)


if __name__ == '__main__':
    socketio.run(app)

When I see chrome network analyzing, I can see the "Access-Control-Allow-Origin" value as null.

According to Flask-socketio documentation: (See API Reference @ http://flask-socketio.readthedocs.io/en/latest/)

Parameters:
...
cors_allowed_origins – List of origins that are allowed to connect to this server. All origins are allowed by default.

Another suggestion I found on searching is using flask-CORS:

app.config['SECRET_KEY'] = 'mysecret'
cors = CORS(app)

socketio = SocketIO(app)

I get the same result.

What is a way to allow Cross-Origin requests with flask-socketio?

Thanks in advance.


回答1:


Cross origin is enabled by default on Flask-SocketIO. My guess is that the way you are testing this is flawed. While running your example application, I can send a request to the main Socket.IO endpoint and I do get the Access-Control-Allow-Origin header in the response:

~ $ http http://localhost:5000/socket.io/
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 119
Content-Type: application/octet-stream
Date: Fri, 01 Jun 2018 17:10:01 GMT
Set-Cookie: io=dd8d67788df54510830fea64bc82b1fd



+-----------------------------------------+
| NOTE: binary data not shown in terminal |
+-----------------------------------------+



回答2:


Below solve it for me. Interaction from Angular app.

socketio = SocketIO(app, cors_allowed_origins="*")


来源:https://stackoverflow.com/questions/50632723/flask-socketio-failed-to-set-access-control-allow-origin-response-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!