How to handle CORS in flask security in api PART 1

Tired of seeing the red warning under your browser while running your web app?

Often while developing web apps you might make use of a flask backend api and a javascript frontend.

Developing such applications we must take care of CORS.

Cross-Origin Resource Sharing

CORS is an implementation used by browsers to prevent access from non trusted origins and domains. When a request is made to the backend from the frontend the request headers contains a origin. This origin determines if the request is valid or not , if the origin is allowed by the server it passes through or else it is blocked by the browser.

Enabling CORS in flask api

Let us build a simple api using flask

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route("/")
def home():
    return jsonify(
        {
            "message": "Home page returned successfully"
        }
    )

@app.route('/delete', methods=['POST'])
def delete_resource():
    # Simulate deletion of a resource
    resource_id = request.form.get('resource_id')
    # Returning a message of deletion
    return jsonify({'message': f'Resource {resource_id} deleted successfully'})

if __name__ == '__main__':
    app.run(debug=True)

On running the api head to localhost:5000

We write a frontend html which sends a request to the backend api

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS Demo</title>
</head>
<body>
    <h1>CORS Demo</h1>
    <label for="resource_id">Resource ID:</label>
    <input type="text" id="resource_id" name="resource_id">
    <button onclick="deleteResource()">Delete Resource</button>
    <script>
        function deleteResource() {
            var resourceId = document.getElementById("resource_id").value;
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "http://localhost:5000/delete", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log(xhr.responseText);
                }
            };
            xhr.send("resource_id=" + resourceId); // Pass the resource_id input value
        }
    </script>
</body>
</html>

Navigating to the web page on hitting the form we face an error

ON running the inspect element

To fix this error we install flask cors package

pip3 install flask-cors

Make use of the CORS package to update this part in the codebase

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

Run the frontend once again

On running inspect element

The message appears to be successful.

If you like my content please comment and share and follow me.