Explain Codes LogoExplain Codes Logo

How to enable CORS in flask

javascript
cross-origin-resource-sharing
flask
cors
Alex KataevbyAlex Kataev·Feb 17, 2025
TLDR

You can enable CORS in your Flask project by including the flask_cors extension. Firstly, run the installation command pip install flask_cors. Then, incorporate it into your Flask app to enable cross-origin requests:

from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) # This magic spell enables CORS for your kingdom, I mean...Routes

Voila, your app is now ready to serve cross-origin responses. Surely feels like magic, doesn't it?

Understanding CORS and Flask

Cross-Origin Resource Sharing (CORS) is crucial in today's world of front-end applications and API services. So, it's essential to delve into how to effectively use CORS in Flask.

Enabling CORS for specific routes

Having a specific permission set for different routes? Use the @cross_origin() decorator to enable CORS only for distinct endpoints:

from flask import Flask from flask_cors import cross_origin app = Flask(__name__) @app.route("/wide-open-route") @cross_origin() def wide_open_route(): return "This route is so wide open, you might catch a draft!"

Secure those origins!

While CORS(app) makes development easy by accepting all origins (*), it’s ultra-important to limit origins for production. We don't want any unwelcomed guests, do we?

CORS(app, resources={r"/api/vital-info": {"origins": "http://trusted-domain-only.com"}})

Just like that, you're safe from unfriendly cross-origin mischief.

Preflight requests – Buckle up!

For complex requests, the browsers make a preflight check. Define the OPTIONS method and present them the required headers:

@app.route("/flight-check", methods=['OPTIONS', 'POST']) @cross_origin() def flight_check(): return "Prepare for takeoff!", 200

Control tower – the after_request hook

Part of being an air traffic controller is to modify responses by setting headers in the after_request hook. Similarly, control your Flask app’s CORS responses:

@app.after_request def give_it_all(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') return response

Be an expert with CORS and Flask

Implementing CORS can be tricky sometimes. But with the right guidelines and some common pitfalls to avoid, you can be a pro.

Handling Cross-origin requests with jQuery

When handling cross-origin AJAX requests in the front-end, jQuery is your trustworthy ally:

$.ajax({ url: 'http://your-flask-app.com/data', type: 'GET', // Remember to ensure CORS is enabled on the backend or we can't be friends... said AJAX. });

Whitelisting – The guest list

It's crucial to have a strict guest list for allowed methods and headers to ensure safety:

CORS(app, resources={ r"/api/only-allowed": { "origins": ["http://trusted-guest1.com", "http://trusted-guest2.com"], "methods": ["GET", "POST"], "allow_headers": ["Content-Type", "Authorization"] } })

CORS with Blueprints – For the artists

For bigger projects with Flask Blueprints, Flask-CORS provides easy integration:

from flask import Blueprint from flask_cors import CORS bp = Blueprint('api', __name__) CORS(bp)

Blueprints and CORS, now that's a masterpiece in the making!

Debugging CORS Routes –

To overcome CORS issues, prioritize adding 'Access-Control-Allow-Origin' to resolve these nightmares:

@app.after_request def add_cors_header(response): response.headers['Access-Control-Allow-Origin'] = '*' // Open to the world, but handle with care! return response