Flask-socketio - 未能设置 "Access-Control-Allow-Origin" 响应 header

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

我写了这个简单的 flask-socketio 代码:

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)

当我看到 chrome 网络分析时,我可以看到 "Access-Control-Allow-Origin" 值为 null

根据 Flask-socketio 文档:(参见 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.

我在搜索时发现的另一个建议是使用 flask-CORS:

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

socketio = SocketIO(app)

我得到了相同的结果。

允许 Cross-Origin 请求 flask-socketio 的方法是什么?

提前致谢。

Flask-SocketIO 默认启用跨源。我的猜测是你测试这个的方式是有缺陷的。当 运行 您的示例应用程序时,我可以向主要 Socket.IO 端点发送请求,并且在响应中得到 Access-Control-Allow-Origin header:

~ $ 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 |
+-----------------------------------------+

下面帮我解决。来自 Angular 个应用的互动。

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