我正在为我的项目尝试websockets,这就是为什么我开始学习websockets的原因。我找到了一个页面,并且已经是第一个引导式示例将我带入了这个问题:我成功地创建了一个服务器,并希望通过我的浏览器连接到它,但是它说没有CORS,所以访问被拒绝了(该指南没有给我关于这方面的信息)。经过3天的研究,我现在几乎要辞职了。我在py libs、SO和cptn中找不到有用的信息。谷歌...:(
我的问题是:在哪里添加CORS头,这样我的请求就成功了。我希望你能帮助我植入这个简单的字典...:(
搜索几个py库和指南,看视频,...
#server
from aiohttp import web
import socketio
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
async def index(request):
with open("socketio_client_test.html") as f:
return web.Response(text=f.read(), content_type="text/html")
@sio.on("message")
async def print_message(sid,message):
print("Socket ID:", sid)
print("Nachricht", message)
app.router.add_get("/", index)
if __name__ == "__main__":
web.run_app(app)shell输出:在http://0.0.0.0:8080 ========上运行======== (按CTRL+C退出)
#client - called via firefox
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<button onClick="sendMsg()">Hit Me</button>
<script src="/home/manuel/Python/AllPy/webserver/socketio/socket.io.js"></script>
<script>
const socket = io("http://localhost:8080");
function sendMsg() {
socket.emit("message", "HELLO WORLD");
}
</script>
</body>
</html>浏览器控制台(德语):->原因: CORS-Header缺失
Quellübergreifende (跨境)和Anfrage : der -Quelle-Regel verbietet das Lesen der externen Ressource auf http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MuuNtyl。(Grund: CORS-Kopfzeile 'Access-Control-Allow-Origin‘fehlt)
发布于 2019-11-05 18:53:06
好的,我想我自己知道答案了。
Engine.IO是方法AsyncServer (类socketio)的底层;
使用**kwargs可以传递参数:“-> cors_allowed_origins="*”<-“
因此,服务器文件中的第5行如下所示:
sio = socketio.AsyncServer(cors_allowed_origins="*")
顺便说一句:我想这也适用于"Server“方法。
https://stackoverflow.com/questions/58701580
复制相似问题