0
votes

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

"Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=MrcruFC' 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.

Server:

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

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


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

@app.route("/")
def hello():
    return 'Hello'

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000)
2
What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response?sideshowbarker
Hi thank you for quick reply. It shows 400 bad request. "GET 127.0.0.1:5000/socket.io/… 400 (BAD REQUEST)"Gthu
So yeah, you have a 400 Bad Request problem, not a CORS problem. If you fix the cause of 400 Bad Request problem, you’ll likely find that your existing CORS configuration is already working as expected. See the answer at stackoverflow.com/a/45356752/441757sideshowbarker
Check the server logs on the flask server and see what messages the server is logging there before it sends back that 400 Bad Request error. You haven’t shown any of you frontend code in the question, but that error indicates your frontend code is sending a request to the server in format that the server does not expect. So the server is responding with that 400 Bad Request error to indicate that you need to change your frontend code to send the request (re)formatted in the way the server expects.sideshowbarker

2 Answers

1
votes

You can add an option for creating SocketIO.

socketio = SocketIO(app=app, cors_allowed_origins='*')
-1
votes

You can allow the CORS using the following headers:

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