这是我的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.
我该怎么做才能解决此错误?请帮忙。
答案 0 :(得分:0)
请按照以下步骤操作:
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
。
答案 1 :(得分:0)
我假设您正在对此进行快速测试?
您似乎有一个直接从文件系统打开的客户端文件,因此Web服务器不提供该文件。该文件正在尝试连接到Socket.IO服务器。 Web浏览器默认情况下不允许跨源连接,因此除非您明确告知Socket.IO服务器,否则无法进行从本地托管文件(源“ null”)到服务器(源“ http://localhost:5000”)的连接。您允许它。
您有两种可能的解决方案:
从Flask Web服务器提供HTML / CSS / JS文件。为此,请将它们放在Flask项目的静态文件夹中,然后从其http://localhost:5000地址(例如http://localhost:5000/static/index.html)中打开它们。
配置Flask-SocketIO服务器的cors_allowed_origins
选项以接受来自null
来源的连接。