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?