Solve Cross Origin Resource Sharing with Flask
You can get the results with a simple:
@app.route('your route', methods=['GET'])def yourMethod(params): response = flask.jsonify({'some': 'data'}) response.headers.add('Access-Control-Allow-Origin', '*') return response
Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.
Install flask-cors
pip install -U flask-cors
then after app initialization, initialize flask-cors
with default arguments:
from flask import Flaskfrom flask_cors import CORSapp = Flask(__name__)CORS(app)@app.route("/")def helloWorld(): return "Hello, cross-origin-world!"
It worked like a champ, after bit modification to your code
# initializationapp = Flask(__name__)app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'app.config['CORS_HEADERS'] = 'Content-Type'cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})@app.route('/foo', methods=['POST'])@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])def foo(): return request.json['inputVar']if __name__ == '__main__': app.run()
I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain