Recently we were trying to add CORS headers to a python flask web server to allow our react website to be allowed to make call to APIs hosted in python flask server. Our aim was to make least amount of code change to server and incorporate CORS headers in all the APIs hosted on this server. We tried for 2-3 days and found a really simple ways of doing it.
Here I am sharing the solution. We added a after request handler in flask to add required headers to all the responses after the response is generated.
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
@app.after_request
def add_cors_header(response):
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Headers"] = "*"
return response
if __name__ == '__main__':
app.run(debug=False)
No comments:
Post a Comment