I have an app that uses standard WebSockets with FastAPI, and that works well. Instead of using FastAPI's WebSocket capability, I would like to use Socket.io. I have looked at lots of examples, and while it looks like I have copied the examples almost exactly, I still get a bunch of errors in the command prompt:
←[32mINFO←[0m: 127.0.0.1:56005 - "←[1mOPTIONS /socket.io/?EIO=4&transport=polling&t=ODINHQk HTTP/1.1←[0m" ←[31m400 Bad Request←[0m
←[32mINFO←[0m: 127.0.0.1:56005 - "←[1mGET /socket.io/?EIO=4&transport=polling&t=ODINHQk HTTP/1.1←[0m" ←[31m404 Not Found←[0m
←[32mINFO←[0m: 127.0.0.1:56005 - "←[1mOPTIONS /socket.io/?EIO=4&transport=polling&t=ODINHq1 HTTP/1.1←[0m" ←[31m400 Bad Request←[0m
←[32mINFO←[0m: 127.0.0.1:56005 - "←[1mGET /socket.io/?EIO=4&transport=polling&t=ODINHq1 HTTP/1.1←[0m" ←[31m404 Not Found←[0m
←[32mINFO←[0m: 127.0.0.1:56005 - "←[1mOPTIONS /socket.io/?EIO=4&transport=polling&t=ODINIDT HTTP/1.1←[0m" ←[31m400 Bad Request←[0m
←[32mINFO←[0m: 127.0.0.1:56005 - "←[1mGET /socket.io/?EIO=4&transport=polling&t=ODINIDT HTTP/1.1←[0m" ←[31m404 Not Found←[0m
It GET requests are all a bunch of 404 errors. I have been testing and researching for hours, and nothing seems to work. I have tried the fastapi-socketio package, copying the example exactly, but it is still not connecting. It appears to be a server issue (as opposed to a client issue), since I get these errors when using this tester.
When I test using my own client (created using Dart), I get 403 errors:
←[32mINFO←[0m: ('127.0.0.1', 57251) - "WebSocket /socket.io/" 403
←[32mINFO←[0m: connection failed (403 Forbidden)
←[32mINFO←[0m: connection closed
←[32mINFO←[0m: ('127.0.0.1', 57253) - "WebSocket /socket.io/" 403
←[32mINFO←[0m: connection failed (403 Forbidden)
←[32mINFO←[0m: connection closed
What am I missing?
Here is my code:
from fastapi import FastAPI
from fastapi_socketio import SocketManager
from fastapi.middleware.cors import CORSMiddleware
origins = [
'https://www.piesocket.com',
# IMPORTANT: Add other endpoints here
]
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
sio = SocketManager(
app=app,
cors_allowed_origins=origins
)
@sio.on('join')
async def handle_join(sid, *args, **kwargs):
print('Emitting...')
await sio.emit('test', 'Success!')
print('Success!')
@sio.on('connect')
async def test(sid, *args, **kwargs):
print('Emitting...')
await sio.emit('test', 'Success!')
print('Success!')
@sio.on('test')
async def test(sid, *args, **kwargs):
await sio.emit('hey', 'joe')
This appears to be similar to this issue and this issue, but it is in Python instead of JavaScript.