问题
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