python3中的CORS标头

我正试图为我的项目进入websockets,这就是为什么我开始学习websockets的原因。我找到了一个页面,并且已经有第一个指导示例将我带到了这个问题:我成功创建了一个服务器并想通过浏览器连接到它,但是它说没有CORS,因此访问被拒绝(该指南没有提供任何信息对这个)。经过三天的研究,我几乎要辞职了。我在py库,SO和cptn中找不到有用的信息。 google ....:(

我的问题:在哪里添加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标头

Quellübergreifende(Cross-Origin)Anfrage blockiert:Die Gleiche-Quelle-Regel verbietet das Lesen der externen资源http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MuuNtyl。 (Grund:CORS-Kopfzeile的“访问控制-允许-来源”提示)。

wtuuser 回答:python3中的CORS标头

好吧,我想我自己得到了答案。

Engine.IO是方法AsyncServer(类socketio)的基础;

使用** kwargs可以传递参数:“-> cors_allowed_origins =” *“

所以服务器文件中的第5行是:

sio = socketio.AsyncServer(cors_allowed_origins="*")

顺便说一句:我猜这对于方法“服务器”也很有效。

本文链接:https://www.f2er.com/3163506.html

大家都在问