Makalone LOgman
Makalone LOgman

Reputation: 980

Python Flask SocketIO basic app doesn't work - Failed to read the 'responseText' property from 'XMLHttpRequest'

I have very basic Flask + SocketIO app, but when I try to emit from client, it doesn't get received. My code:

from flask import Flask
from flask_socketio import SocketIO

#Flask setup
app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/')
...

@socketio.on('test')
def test():
    print('received')

@socketio.on('connect')
def connect():
    print('connected!')

def start_flask():
    socketio.run(app, host='127.0.0.1', port=12345, debug=True)

if __name__ == '__main__':
    start_flask()

JS:

var socket = io('http://localhost:36958');

socket.on('connect', function () {
    console.log('connect');
});

function test() {
   console.log('test')
   socket.emit('test');
}
  1. When I refresh - I get "connected" from Python, but not from client/JS console. I just get this error there:
polling-xhr.js:315 Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').
    at n.value (https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.1/socket.io.min.js:6:49490)
    at XMLHttpRequest.hasXDR.e.onreadystatechange (https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.1/socket.io.min.js:6:48706)
  1. When I try to call test() function - it shows 'test' in JS console, but not 'received' in Python.

Thank you.

Upvotes: 1

Views: 440

Answers (2)

Makalone LOgman
Makalone LOgman

Reputation: 980

Solved by downgrading to SocketIO 2

Upvotes: 4

Lucas Campos
Lucas Campos

Reputation: 108

When you consume an API from flask in a different port you need to import CORS to handle the problem with Security, so follow the steps, install flask_cors lib:

pip3 install Flask-Cors

Then in your code:

from flask_cors import CORS
app = Flask(__name__)
socketio = SocketIO(app)
CORS(app)

Upvotes: 0

Related Questions