赞
踩
- import socketio
- from typing import Text
- from urllib.parse import parse_qs
- from fastapi import FastAPI, APIRouter
-
- _sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins= [] )
- _app = socketio.ASGIApp( socketio_server=_sio, socketio_path="socket.io" )
-
- async def connect(sid, *args, **kwargs):
- query_string =args[0]["QUERY_STRING"]
- query_dict = parse_qs(query_string)
- await _sio.enter_room(sid=sid,room=query_dict["roomId"][0])
-
- async def disconnect(sid, *args, **kwargs):
- query_string =args[0]["QUERY_STRING"]
- query_dict = parse_qs(query_string)
- await _sio.leave_room(sid=sid,room=query_dict["roomId"][0])
-
-
-
- _sio.on('connect',connect)
- _sio.on('disconnect',disconnect)
-
- def SocketMnager(app:APIRouter|FastAPI):
- app.mount("/ws",_app)
- app.sio = _sio
-
-
-
- from fastapi.middleware.cors import CORSMiddleware
- from fastapi import FastAPI
- app = FastAPI()
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
- SocketMnager(app)
- import uvicorn
- uvicorn.run("__main__:app",host="0.0.0.0",port=3000,reload=False)
前端出现错误1
The 'Access-Control-Allow-Origin' header contains multiple values'*, *', but only one is allowed.
- # 将前文中的cors_allowed_origins设置为[]
- # 这是由于 CORSMiddleware 与socketio 重复设置请求头导致
-
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。