How to fix "Access-Control-Allow-Origin" error in a python socket-io server

Question:

I’m creating a project that uses Vue.js (as a client) and Python (as a server). Python is used for some calculation and the Vue.js is used for the interface. I’m connecting them using python-socketio (https://python-socketio.readthedocs.io/en/latest/) and Vue-socket.io (https://github.com/MetinSeylan/Vue-Socket.io). Some weeks ago it was working just fine. The connection and communication was happening succefully. But a couple days ago I tried running the same code again and this error appeared:

► Access to XMLHttpRequest at shttp://localhost:2003/socket.io/?EI0.38transport.polling&t=Mom6k2V' from origin 'http://1 :1 ocalhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
► GET http://localhost:2003/socket.io/?EI0=3&transport=polling&t=Mom6k2V net::ERR FAILED vue-socketio.js?5132:8

I tried using old repositories that i knew for sure that were working but I got the same problem.

I tried running the same code in another computer and in a Raspberry Pi and got the same problem.

I tried running chrome with –disable-web-security in order to disable cors but I got the following error:

► WebSocket connection to 'ws://localhost:2003/socket.io/? vue-socketio.js?5132:10 EI0.3&transport=websocket&sid=7111830544fa4dfd98c3424afd25c10e failed: Error during WebSocket handshake: Unexpected response code: 400 

Server

# -*- coding: utf-8 -*-
import eventlet
import socketio
import numpy as np
import json
import serial
import threading
from scipy.integrate import odeint

sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})

@sio.on('connect')
def connect(sid, env):
    print('conectado ', sid)

@sio.on('disconnect')
def disconnect(sid):
    print('desconectado ', sid)

# Other functionalities in the code 
#...

if __name__ == '__main__':
    print('Inicnando...')
    thread = threading.Thread(target=leitura_dados, args=(ser,))
    thread.start()
    eventlet.wsgi.server(eventlet.listen(('', 2003)), app)

Connection in the client

Vue.use(new VueSocketIO({
  debug: false,
  connection: 'http://localhost:2003'
}))

I expected it to work as it did before. Without any CORS error or error during handshake. I have no idea why it suddenly stopped working.

Asked By: Gustavo Cesário

||

Answers:

Looking a little bit deeper into the docs (https://python-socketio.readthedocs.io/en/latest/api.html?highlight=cors#server-class) I finally found the answer.
Instead of:

sio = socketio.Server()

Use

sio = socketio.Server(cors_allowed_origins='*')
Answered By: Gustavo Cesário

server.py

sio = socketio.AsyncServer(cors_allowed_origins=['*']) # * is bad

client.js
– Extra arg required:

let socket = io("http://localhost:8080",
{transports: ['websocket', 'polling', 'flashsocket']}
)

copied!
https://github.com/socketio/socket.io-client/issues/641#issuecomment-38276289

Answered By: Ahmed Shehab

This is how i am using socketio with my django application

setting.py

ALLOWED_HOSTS: [ '0.0.0.0', 'localhost:3000']

import the allowed_hosts list from settings and prefix with http://

async_mode = 'asgi'
mgr = socketio.AsyncRedisManager(settings.REDIS_URL)
allowed_hosts = ['http://' + str(i) for i in settings.ALLOWED_HOSTS]


asio = socketio.AsyncServer(
    logger=True,
    cors_allowed_origins=allowed_hosts,
    async_mode=async_mode,
    client_manager=mgr,
    # engineio_logger=True
)
Answered By: Lohith
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.