1

I am using frontend (in reactJS) (localhost:8080) to call the flask API (localhost:8000) as specified below:

def _build_cors_prelight_response():
    response = make_response()
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Headers", "*")
    response.headers.add("Access-Control-Allow-Methods", "*")
    return response

def event_stream():
    while True:
        # wait for source data to be available, then push it
        yield 'data: {}\n\n'.format(get_message())

#from: https://stackoverflow.com/questions/25594893/how-to-enable-cors-in-flask
@app.route('/api/events', methods=["GET","OPTIONS"])
def events():
    if request.method == "OPTIONS":  # CORS preflight
        return _build_cors_prelight_response()
    elif request.method=="GET":
        return Response(event_stream(), mimetype="text/event-stream")

Although I have specified Access-Control-Allow-Origin in the header, I still get cors error in chrome (v. 81.0.4044.138)

enter image description here

Interestingly if I omit the line response.headers.add("Access-Control-Allow-Origin", "*") above, I would get a different error

enter image description here

In my flask endpoint, this is what I see in the console: enter image description here

How to resolve the issue?

william007
  • 17,375
  • 25
  • 118
  • 194
  • Hi, interestingly I had the exact issue working on a `react/django` project while using `Chrome version 84.0.4147.105`. It persisted despite all other solutions that I tried until i installed this chrome extension [Allow CORS: Access-Control-Allow-Origin](https://mybrowseraddon.com/access-control-allow-origin.html). I honestly couldn't understand why. Try it too, and let me know how it turns out! – MwamiTovi Aug 05 '20 at 16:15
  • @MwamiTovi Same here! I am blindly using that extension to make it work. – william007 Aug 06 '20 at 01:00
  • So then it worked for you too? Have you investigated this issue with say firefox? – MwamiTovi Aug 06 '20 at 01:42
  • @MwamiTovi yes, I get it worked before I asked this question, but that’s not what I want – william007 Aug 06 '20 at 01:43
  • Ok, i see your point. – MwamiTovi Aug 06 '20 at 01:46

0 Answers0