'Getting "connection failed (403 Forbidden)" error while make connection to python-socketio(socket.io)

I wanted to make a connection on the socket.io so I used python-socket.io in the backend (FastAPI) and socket.io-client for the frontend(React.js) but I have been getting connection failed error (403 Forbidden).

Front End

import io from 'socket.io-client'

const [message, setMessage] = useState('')
const [socket, setSocket] = useState<any>(null)
const [response, setResponse] = useState<any>(['Static Message'])

const handleSocketCall = useCallback(() => {
  const client_id: any = localStorage.getItem('_id')
  const socketio = io('http://localhost:8000/', {
    transports: ['websocket', 'polling'],
    reconnection: false,
    rejectUnauthorized: false,
  })

  socketio.emit('connection', client_id)
  setSocket(() => socketio)
}, [])

useEffect(() => {
  if (typeof socket !== null) {
    handleSocketCall()
  }
}, [])

BackEnd

from mongoengine import connect
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import json
import socketio

from models.users import Users
from routes.auth import router 
from routes.user import user_router

app = FastAPI()
sio = socketio.AsyncServer(cors_allowed_origins='*', async_mode='asgi', engineio_path='/'  )
socketio_app = socketio.ASGIApp(sio, app)

sio.transports = ["xhr-polling"];
sio.polling_duration = 10;


app.add_middleware(
      CORSMiddleware,
      allow_origins=["*"], # Allows all origins
      allow_credentials=True,
      allow_methods=["*"], # Allows all methods
      allow_headers=["*"], # Allows all headers
)

# storing online user's socket id so that we can send message to them
connected_user = []

app.include_router(router)
app.include_router(user_router)

# connection to the database
connect('LazzyMe', host='localhost', port=27017)

@sio.event
def connect(sid, environ):
    print("connect ", sid)
    raise ConnectionRefusedError('authentication failed')


@sio.on('connection')
async def connection(sid, client_id):
    already_connected = False
    for user in connected_user:
        if user['client_id'] == client_id:
            already_connected = True
            current_user = user
            current_user['sid'].append(sid)
            connected_user.remove(user)
            connected_user.append(current_user)
            break

    if not already_connected:
        connected_user.append({'sid': [sid], 'client_id': client_id})
    await sio.emit('connected')


@sio.on('message')
async def chat_message(sid, data):
    sio.enter_room(sid, 'chats')
    reciving_user = []
    for user in connected_user:
        if user['client_id'] == data['id']:
            reciving_user=user['sid']
            
    for user in reciving_user:
        sio.enter_room(user, 'chats')

    await sio.emit('response',  data['message'], room='chats', skip_sid=sid)

    sio.leave_room(sid, 'chats')
    for user in reciving_user:
        sio.leave_room(user, 'chats')


@sio.event
def connect_error(data):
    print("The connection failed!", data)

@sio.event
def disconnect(sid):
    for user in connected_user:
        if sid in user['sid']:
            user['sid'].remove(sid)
    print('disconnect ', sid, connected_user)


@app.get('/')
def Home():
    return {"message": "Hello World"}

It worked yesterday with the same code, but when I ran the server today, I had this issue.

Thank You.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source