How to Use flask-cors for Cross-Origin Requests in Flask
To use
flask-cors, install it via pip, then import and wrap your Flask app with CORS(app) to enable cross-origin requests. You can customize origins and routes by passing options to CORS().Syntax
The basic syntax to enable CORS in a Flask app is to import CORS from flask_cors and wrap your Flask app instance with it. You can pass optional parameters to control which origins or routes allow cross-origin requests.
CORS(app): Enables CORS for all routes and origins.CORS(app, resources={r"/api/*": {"origins": "*"}}): Enables CORS only for routes matching/api/*and allows all origins.
python
from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) # Enable CORS for all routes and origins
Example
This example shows a simple Flask app with CORS enabled globally. It allows any website to make requests to the Flask server.
python
from flask import Flask, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) # Enable CORS for all routes @app.route('/data') def data(): return jsonify({'message': 'Hello from Flask with CORS!'}) if __name__ == '__main__': app.run(debug=True)
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
Common Pitfalls
Common mistakes when using flask-cors include:
- Not installing the package with
pip install flask-cors. - Forgetting to wrap the Flask app with
CORS(app), so CORS headers are missing. - Using
CORSbut not configuring origins properly, which may expose your API unintentionally. - Applying CORS only to some routes but expecting it globally.
Always test your API from a different origin to confirm CORS headers are sent.
python
from flask import Flask from flask_cors import CORS app = Flask(__name__) # Wrong: forgetting to enable CORS @app.route('/') def home(): return 'No CORS headers here' # Correct way: # CORS(app) # Enables CORS globally
Quick Reference
Here is a quick summary of common flask-cors usage options:
| Option | Description | Example |
|---|---|---|
| CORS(app) | Enable CORS for all routes and origins | CORS(app) |
| resources | Limit CORS to specific routes | CORS(app, resources={r"/api/*": {"origins": "*"}}) |
| origins | Specify allowed origins | CORS(app, origins=["https://example.com"] ) |
| methods | Limit allowed HTTP methods | CORS(app, methods=["GET", "POST"] ) |
| supports_credentials | Allow cookies and credentials | CORS(app, supports_credentials=True) |
Key Takeaways
Install flask-cors and wrap your Flask app with CORS(app) to enable cross-origin requests.
Customize CORS behavior by passing options like resources and origins to CORS().
Always test your API from different origins to verify CORS headers are correctly applied.
Avoid exposing your API unintentionally by restricting allowed origins and methods.
Remember to install flask-cors via pip before importing and using it.