vue.js 如何修复python socket-io服务器中的“Access-Control-Allow-Origin”错误

mwngjboj  于 2023-03-03  发布在  Vue.js
关注(0)|答案(3)|浏览(146)

我正在创建一个使用Vue.js(作为客户端)和Python(作为服务器)的项目。Python用于一些计算,Vue.js用于接口。我使用python-socketio(https://python-socketio.readthedocs.io/en/latest/)和www.example.com将它们连接Vue-socket.io起来(https://github.com/MetinSeylan/Vue-Socket.io)。几周前它工作得很好。连接和通信都很成功。但是几天前我尝试再次运行相同的代码,出现了以下错误:

► 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

我尝试使用旧的存储库,我知道肯定是工作,但我得到了同样的问题。
我试着在另一台电脑和树莓派中运行同样的代码,也遇到了同样的问题。
我试着运行chrome with --disable-web-security来禁用cors,但我得到了以下错误:

► 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

服务器

# -*- 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)

客户端中的连接

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

我期望它能像以前一样工作。没有任何CORS错误或握手过程中的错误。我不知道它为什么突然停止工作。

dgenwo3n

dgenwo3n1#

通过更深入地研究这些文档(https://python-socketio.readthedocs.io/en/latest/api.html?highlight = cors #server-class),我终于找到了答案。

sio = socketio.Server()

用途

sio = socketio.Server(cors_allowed_origins='*')
hc2pp10m

hc2pp10m2#

server.py

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

client.js -需要额外的参数:

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

已复制https://github.com/socketio/socket.io-client/issues/641#issuecomment-38276289

li9yvcax

li9yvcax3#

这就是我如何使用socketio与我的django应用程序
setting.py

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

从设置导入allowed_hosts列表,并使用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
)

相关问题