CORS - Cross-Origin Resource Sharing

CORS helps maintain data integrity between the API server and the client for the API request.

The idea behind using CORS is that the server and client should have enough information about each other so that they can authenticate each other, and transfer data over a secure channel using the HTTP header.

When a client makes an API call, it is either a GET or POST request, where the body is usually text/plain with headers called Origin--this includes protocol, domain name, and port with respect to the requesting page. When the server acknowledges the request, and sends the response along with the Access-Control-Allow-Origin header to the same Origin, it makes sure the response is received at the correct Origin.

In this way, resource sharing happens between Origins.

Almost all browsers now support CORS, which includes IE 8+, Firefox 3.5+, and Chrome.

Now, since we have the web application ready, but it is not CORS-enabled yet, let's enable it.

Firstly, you need to install the module for CORS in Flask using the following command:

$pip install flask-cors

The preceding package exposes a Flask extension which, by default, enables CORS support on all the routes for all Origins and methods. Once the package is installed, let's include it in app.py as follows:

    from flask_cors import CORS, cross_origin 

To enable CORS, you need to add the following line:

   CORS(app) 

That's it. Now this CORS is enabled for all the resources in your Flask application.

In case you want to enable CORS on specific resources, then add the following code with your specific resource:

   cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) 

Currently, we don't have a domain setup, but we are working at the localhost level. You can test CORS by adding a custom domain in the domain name server as follows:

   127.0.0.1    <your-domain-name> 

Now, if you try to access this <your-domain-name>, it should be able to work properly with this domain name, and you will be able to access the resource.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.85