Maetran
Maetran

Reputation: 11

CORS headers in python3

i am trying to get into websockets for my project, thats why i started to learn about websockets. i found a page and already the first guided example brought me to this issue: i successfully create a server and want to connect to it via my browser, but it says there is no CORS so the access is denied (the guide gives me no information about this). after my research for 3 days i am now almost resigning. i cant find helpful informations in the py libs, SO, and cptn. google.... :(

my question: where to add the CORS header, so my request is successful. i hope you can help me with implenting this simple dict... :(

searching several py libs and guides, watching videos,...

#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 output: ======== Running on http://0.0.0.0:8080 ======== (Press CTRL+C to quit)

#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>

browser console (in german): -> Reason: CORS-Header missing

Quellübergreifende (Cross-Origin) Anfrage blockiert: Die Gleiche-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).

Upvotes: 0

Views: 1131

Answers (1)

Maetran
Maetran

Reputation: 11

ok i think i got the answer myself.

Engine.IO is underlying of the method AsyncServer (class socketio);

with **kwargs you can pass the param: " -> cors_allowed_origins="*" <- "

so line 5 in the serverfile is like:

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

btw: i guess this works as well for the method "Server".

Upvotes: 1

Related Questions