0

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)
sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
Gthu
  • 27
  • 5
  • 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 Sep 25 '19 at 05:49
  • Hi thank you for quick reply. It shows 400 bad request. "GET http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=MrcruFC 400 (BAD REQUEST)" – Gthu Sep 25 '19 at 05:51
  • 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 https://stackoverflow.com/a/45356752/441757 – sideshowbarker Sep 25 '19 at 13:19
  • 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 Sep 25 '19 at 13:22

2 Answers2

1

You can add an option for creating SocketIO.

socketio = SocketIO(app=app, cors_allowed_origins='*')
aquilegia
  • 26
  • 1
-1

You can allow the CORS using the following headers:

header = response.headers
header['Access-Control-Allow-Origin'] = '*'
alessiosavi
  • 1,729
  • 1
  • 9
  • 26