0

I'm having issues on my application that has been deployed to Heroku. When I was developing it on localhost, I didn't get this error, but once I deployed it, it spontaneously throws this error:

Access to fetch at 
'https://frontend.herokuapp.com' from origin 
'https://backend.herokuapp.com' has been blocked 
by CORS policy: No 'Access-Control-Allow-Origin' header is present 
on the requested resource. If an opaque response serves your needs, 
set the request's mode to 'no-cors' to fetch the resource with CORS 
disabled.

Simplified version of my Flask server:

from flask import Flask, request, make_response, jsonify, url_for, 
redirect, render_template
from flask_cors import CORS, cross_origin
import flask
import json

app = Flask(__name__)
CORS(app)

@app.route('/api/action', methods=['GET', 'POST'])
@cross_origin()
def prescription(response={}):

    # POST request
    if request.method == 'POST':
         print('score POST request')
         response = request.get_json()
         data = json.loads(response.get('data'))
         rating = a_super_cool_feature
         return jsonify(rating), 200

     # GET request
    else:
        print('GET request')
        return getScore(response)

@app.route('/api/score', methods=['GET', 'POST'])
@cross_origin()
def scoreHandler(response={}):

    # POST request
    if request.method == 'POST':
         print('Incoming..')
        response = request.get_json()
        parseResponse(response)
        return str(getScore(response)), 200


    # GET request
    else:
        return getScore(response)


@app.route('/test')
def test_page():
    # look inside `templates` and serve `index.html`
    return render_template('index.html')

if __name__ == "__main__":
     app.debug=True
     app.run()

My front-end is a React application. These two servers run on separate Heroku servers and I'm using the free version so I only get one dyno at a time (in case this could cause this error).

The interesting thing is this:

About half the time, when these POST requests are called on the deployed Heroku app, the error is thrown. Otherwise, it works no problem. Any ideas on fixing this?

  • Possible duplicate of [How to enable CORS in flask and heroku](https://stackoverflow.com/questions/25594893/how-to-enable-cors-in-flask-and-heroku) – Selcuk Aug 20 '19 at 04:38

3 Answers3

0

You could use this snippet to enable cors app wide.

from flask import Flask
from flask_cors import CORS
app = Flask(__name__) CORS(app)
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0

Really weird psuedo fix. Basically it was giving me this error about 40% of the time I made the POST request to the Flask backend, then I added

 app.config['CORS_HEADERS'] = 'Content-Type'

Under the:

app = Flask(__name__)
CORS(app)

And this did not fix the issue completely. However; now this error is only thrown about 5% of the time when requests are made to the back-end. See other answer for actual fix.

  • What do you mean by the percentages? Are you making it from localhost or some client like postman where it will work by default but not with production application. – Vishnudev Krishnadas Aug 20 '19 at 19:19
  • In postman it works. Here's what I mean with the percentages: I'll deploy the application, click the button in the app that sends a POST request, look at the console in inspect elements, and most of the time it works just fine. However, when I refresh the page and click the button again, about 5% of the time I would do this the console gave me the 'No Access-Control-Allow-Origin' headers error. – Sean Kearney Aug 21 '19 at 20:48
0

Okay now I actually fixed it. I bought the "Hobby" dyno type in Heroku and I never get the error now. I think it just has to do with the other server not being up and running when I make the request because I can only have one dyno running at a time with the free version. Thus it somehow timed out and gives that error.

With the Hobby dyno type my backend is always running so when I make a request it no longer times out and gives that error.