400 Bad Request error with flask server react client for socketio

Trying to create a socketio link between flask server and reactjs client. It shows this error

“Access to XMLHttpRequest at ‘‘ from origin ‘http://localhost:3000‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

I have tried including CORS from the flask cors documentation but it still doesnot work.


from flask import Flask, Response
from flask_cors import CORS
from flask_socketio import SocketIO

app = Flask(__name__)
cors = CORS(app)

def handle_my_custom_event():
    socket.emit('outgoing data',{num: '10'})

def hello():
    return 'Hello'

if __name__ == '__main__':
    socketio.run(app, host='', port=5000)

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can add an option for creating SocketIO.

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

Solution 2

You can allow the CORS using the following headers:

header = response.headers
header['Access-Control-Allow-Origin'] = '*'

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply