Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and Flask with Socket.IO - CORS problem

I'm trying to make a Flask server (port 5000) that has a socket.io connection with a React client (port 3000). When I try to execute the server script (shown below), I get an error that says "http://localhost:3000 is not an accepted origin" even though I am using CORS.

server-test.py:

from flask import Flask
from flask_socketio import SocketIO, emit
from flask_cors import CORS, cross_origin

import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SECRET_KEY'] = os.environ.get('SECRET')
socketio = SocketIO(app)
CORS(app)

@socketio.on('connect')
@cross_origin()
def handle_connection():
  emit('server-client', 'Test message')


@socketio.on('client-server')
@cross_origin()
def handle_client_msg(msg):
  print("\n" + str(msg))


if __name__ == '__main__':
  app.run(host="localhost", port=os.environ.get('PORT'))
  socketio.run(app)

App.jsx:

import { io } from 'socket.io-client';

// ...

useEffect(() => {
  const socket = io('http://localhost:5000');

  socket.on('server-client', msg => {
    alert(msg);
    socket.emit('client-server', 'Client: Message received!');
  });
}, []);

Error message in WSL terminal:

 * Serving Flask app 'server-test' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://localhost:5000/ (Press CTRL+C to quit)
http://localhost:3000 is not an accepted origin. (further occurrences of this error will be logged with level INFO)
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZQ HTTP/1.1" 400 -
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZS HTTP/1.1" 400 -
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZR.0 HTTP/1.1" 400 -
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZR HTTP/1.1" 400 -
like image 690
pmorim Avatar asked Oct 20 '25 13:10

pmorim


1 Answers

The Flask SocketIO documentation says this:

If an incoming HTTP or WebSocket request includes the Origin header, this header must match the scheme and host of the connection URL. In case of a mismatch, a 400 status code response is returned and the connection is rejected.

and this:

If necessary, the cors_allowed_origins option can be used to allow other origins. This argument can be set to a string to set a single allowed origin, or to a list to allow multiple origins. A special value of '*' can be used to instruct the server to allow all origins, but this should be done with care, as this could make the server vulnerable to Cross-Site Request Forgery (CSRF) attacks.

So instead of this:

socketio = SocketIO(app)

you could do this:

socketio = SocketIO(app, cors_allowed_origins="*")

Unrelated to the cors issue, but I also added return statements to the functions. Without returning something I got:

TypeError: The view function did not return a valid response.

Seems to be required if using the @cross_origin() decorators, so you could also remove those and then you don't need the return statements.

like image 129
Bas van der Linden Avatar answered Oct 22 '25 03:10

Bas van der Linden