Configure CORS in Flask
CORS can be defined as:
Cross-Origin Resource Sharing (CORS (en-US)) is a mechanism that allows a server to be configured to obtain permissions to access selected resources from that server to a different origin (domain).
And this is according to the definition that we have in Mozilla;
https://developer.mozilla.org/es/docs/Web/HTTP/CORS
As an example we have if we have an App in Flask, we create a Rest Api as we created in the complete course and we want to consume it from an app in Vue:
By default, the server will block any request that comes from another domain, which makes all the sense in the world since in 99.99 percent of the cases we will be interested in ensuring that no other app or domain can perform operations on our app. .
Although in this interconnected world, we create a web app, but then we create other apps to improve its access depending on the device, and therefore we create additional apps, whether mobile with Flutter, Vue Native, React, Android Native, Vue ... we need to open that door to be able to communicate these apps with our personal cloud, and in these cases we can use CORS to open this door in a controlled and secure way;
Being Flask a micro framework, we have to install a dependency or package to be able to use this feature, in this entry we select the following:
https://flask-cors.readthedocs.io/en/latest/
Remember to have your app created, a hello world in Flask, and your rest api in Flask.
which once installed:
pip install flask-cors
We carry out the typical configurations
#CORS
from flask_cors import CORS
cors = CORS(app, resources={r"/api/*": {"origins": "http://localhost:8080"}})
- /api/* refers to which part of the domain you are going to allow sharing; generally you don't need to enable access to the whole app, but only to your rest api, which usually starts with the suffix of "api" which is what we enable
- In the origin, we can place them all with *, or one in particular; in this case, we place the localhost and the port 8080 which is the Vue app in development mode
Now with this, from our app in Vue, we can consume our rest:
fetch("http://localhost:5000/api/products/")
.then((res) => res.json())
.then((res) => (this.products = res));
And see the response from the browser:
Without the use of CORS in Flask:
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter