I am working on a personal chat app using fastapi ,python socketio and React . I have mounted the socketio app on startup event of fastapi. Now there is this issue that when i try to connect socket there is some or the other cors error, such as that of duplicated origin, mixed content or access-control-allow-origin is null, or loclahost:3000 is not an accepted origin, or headers cannot be ““. For the CorsMiddleware i have tried different entries in allow_origins such as passing in ““, or particular ip with their ports but to no avail.Also for socket Asyncserver, when I keep the cors_allowed_origins as an empty list it seems to work as cors is disabled for the socket but I want to allow only specific addresses.I am quite stuck and have also referred to other posts and articles . Any help is highly appreciated. Thanks
Here is my code for fastapi startup event and socket server:
#app.py
@app.on_event("startup")
async def init_resources() -> None:
socketio_server = SocketIOServer().init(room_namespace=room_namespace)
sio_app = socketio.ASGIApp(
socketio_server=socketio_server, socketio_path="", other_asgi_app=app
)
app.mount("/socket.io", sio_app)
return app
#socket_server.py
def init(self, room_namespace: RoomNamespace, *args: Any, **kwargs: Any) -> socketio.AsyncServer:
self.sio = socketio.AsyncServer(
async_mode="asgi",
cors_allowed_origins=[],
logger=True,
engineio_logger=True,
)
self.sio.register_namespace(room_namespace)
return self.sio
React code for socket
const socket = io(import.meta.env.VITE_SOCKET_SERVER_URI, {
// transports: ['Socket', 'polling', 'flashsocket'],
auth: {
token: tokens?.access
},
withCredentials: true
});
Service Bucket is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.