这是我的 first.py
文件。
from flask import Flask
from flask_socketio import SocketIO,send
app=Flask(__name__)
app.config['SECRET_KEY']='myscret'
socketio=SocketIO(app)
@socketio.on('message')
def handlemessage(msg):
print('Message:'+msg)
send(msg,broadcast=True)
if __name__=='__main__':
socketio.run(app,debug=True)
这就是 index.html
文件。
<html>
<head>
<title>Chat room</title>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" >
$(document).ready(function()
{
var socket=io.connect('http://127.0.0.1:5000');
socket.on('connect',function()
{
socket.send('User has connected');
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbtn">Send</button>
</body>
</html>
但当我运行 first.py
档并打开 index.html
在浏览器中出现以下错误。
Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=N9J4bHD' from
origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on
the requested resource. index.html:1
GET 127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=N9J4bHD:1 Failed to load resource:
net::ERR_FAILED socket.io.min.js:2
Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?
EIO=3&transport=polling&t=N9J4bQM' from origin 'null' has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=N9J4bQM:1 Failed to load resource:
net::ERR_FAILED
Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?
EIO=3&transport=polling&t=N9J4c8L' from origin 'null' has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
我应该怎么做才能解决这个错误?请大家帮忙。
我想你是在用这个运行一个快速测试吧?
你似乎有一个直接从文件系统打开的客户端文件,所以它不是由你的Web服务器服务的。这个文件正试图连接到Socket.IO服务器。Web浏览器默认不允许跨源连接,所以从本地托管文件(源'null')连接到你的服务器(源'')。http:/localhost:5000')是不可能的,除非你明确地告诉Socket.IO服务器你允许它。
您有几种可能的解决方案。
从你的Flask web服务器上服务你的HTMLCSSJS文件。要做到这一点,将它们放在Flask项目的静态文件夹中,然后从它们的 http:/localhost:5000 地址(例如: http:/localhost:5000staticindex.html。).
配置 cors_allowed_origins
Flask-SocketIO服务器的选项,以接受来自的连接。null
原产地。
请按照以下步骤操作。
pip install -U flask-cors
app=Flask(__name__)
from flask_cors import CORS
CORS(app)
SocketIO
像下面这样。socket = SocketIO(app, cors_allowed_origins="*")
socket
像下面这样的装饰器。@socket.on('message')
def handlemessage(msg):
注意: 第4点,应该只在开发阶段考虑。即使在开发阶段,如果你还想缩小传入请求的范围,你可以尝试。cors_allowed_origins='null'
,配合你的设置。但是,我还是不建议在生产阶段这样做。在这种情况下,你可以配置 cors_allowed_origins
与托管地址相应。