javascript - 如何将 Javascript 客户端连接到 Python-SocketIO 服务器?

标签 javascript python django socket.io

我刚刚开始使用 Python-SocketIO,我创建了一个示例服务器,它看起来像这样:

import eventlet
import socketio

sio = socketio.Server()

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

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

@sio.on('msg')
def message(sid, data):
    print('message ', data)

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

if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('', 5000)), app)

然后,我有一个在 Django 应用程序上运行的 HTML 文件,我想将该客户端连接到我的 Python-SocketIO 服务器:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>

socket = io.connect('');

socket.on('connect',function() {
  console.log('Client has connected to the server!');
});

socket.on('msg',function(data) {
  console.log('Received a message from the server!',data);
});

socket.on('disconnect',function() {
  console.log('The client has disconnected!');
});

// Sends a message to the server via sockets
function send(message) {
  socket.send('msg',message);
};

</script>

问题是,在我的客户端,我不断收到以下错误:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2:1 Failed to load resource: net::ERR_FAILED

我的 Django 服务器正在运行 on http://127.0.0.1:8000/ 。谁能帮我找出我做错了什么?

最佳答案

在服务器上设置 CORS header :

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

( Source )

关于javascript - 如何将 Javascript 客户端连接到 Python-SocketIO 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154295/

相关文章:

javascript - 如何在完整日历插件中禁用上个月

javascript - 通过 setInterval 添加输入不起作用

python - 使用 Python 的 SQL 查询不起作用

python - 我试图使我的数据平衡,因为我的目标变量具有多类,并且我想对其进行过采样以使我的数据平衡

python - tastypie api 不在 json 结果中显示 ForeignKey

mysql - 如何在 django 2.1.5 中显示 mysql 8 的数据?

django - 无法在部署服务器上启用 huey 服务

Internet Explorer 6,7,8, "is null or not an object "上的 JavaScript 错误

javascript - React-Redux 类型错误 : Cannot read property 'setStatus' of undefined

python - 在 Dash 中的回调中清除组件