Adding support to CORS into our Flasky apps

First of all have an idea about whats CORS means and what is this all about.

Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests.

There are to many options to do that, I'm gonna show to you three of them:

First option

We can simply add a specific header allowing all origins into our responses.

resp.headers['Access-Control-Allow-Origin'] = "*"
return resp

Second option

And the second option is using flask-cors extension to allow us to use a decorator in our method.

@cross_origin() # allow all origins.
def helloWorld():
  return "Hello, cross-origin-world!"

On the link above you will find how to install this extension

Third option

If your are building a RESTful app then you may considerer use flask-restful extension which actually support CORS by default.

You will not find anything about it on their documentation yet beucase they just release this functionality, but you can have some information about it on this pull request.

If you wanna use this feature you should do something like this:

from flask_restful.utils import cors

app = Flask(__name__)
api = restful.Api(app)

class HelloWorld(restful.Resource):
    def get(self):
        return {'hello': 'world'}