14

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.

3
  • Is that 'http://1 :1 ocalhost:8080' origin correct or is that a copypaste error? Commented Aug 20, 2019 at 17:58
  • Also, is the code you provided the one that generated the errors shown above? Commented Aug 20, 2019 at 17:59
  • @jjmontes it's a copy paste error, it should be "localhost:8081". And yes, that was the code that I was using when I got those errors. Commented Aug 20, 2019 at 18:54

4 Answers 4

34

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='*')
Sign up to request clarification or add additional context in comments.

1 Comment

"*" not working for me. Still puts up cors error
11

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

4 Comments

Adding the transports extra arg solved it for me
@Sahar: Any thoughts about deployment servers !
This is what eventually solved my issue
Thank you so much, somehow I did not read anything about setting the transport args yet, but now it works!
1

This is how I am using Socket.io with my Django application:

# setting.py
ALLOWED_HOSTS = ['0.0.0.0', 'localhost:3000']

Then, import the ALLOWED_HOSTS list from settings.py and prefix each allowed host 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
)

Comments

-1

you can also use Cors-removing extensions that are working with your respective browser.

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
Cors-removing extensions make the code not portable, and also puts up a major security risk. I wouldn't recommend doing this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.