Flask-CORS is a Flask extension that enables Cross-Origin Resource Sharing (CORS), allowing web applications hosted on different origins to communicate with a Flask backend. It is commonly used when building REST APIs that interact with frontend frameworks such as React, Angular, or Vue.
CORS
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls whether a web application can access resources from a different origin. An origin consists of three components:
- Protocol (http or https)
- Domain name
- Port number
Example:
Frontend: http://localhost:3000
Backend: http://localhost:5000
Since the port numbers are different, they are considered different origins. By default, browsers block communication between them unless CORS is enabled.
Features of Flask-CORS
- Allow communication between frontend and backend applications running on different origins.
- Enable API access from web and mobile applications.
- Simplify handling cross-origin AJAX requests.
- Control which domains can access a Flask application.
Installation
It is recommended to use a virtual environment before installing Flask-CORS. Create and Activate a Virtual Environment using following commands:
python -m venv venv
venv\Scripts\activate
Install Flask-CORS using following command:
pip install Flask-Cors
Enable CORS in the Flask
The simplest way to enable CORS is to initialize the extension for the entire application.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def home():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Explanation:
CORS(app)enables CORS for all routes.- Every endpoint can now receive requests from different origins.
- Flask automatically sends the required CORS headers.
Enable CORS for Specific Routes
If only certain routes require cross-origin access, use the @cross_origin() decorator.
from flask import Flask
from flask_cors import cross_origin
app = Flask(__name__)
@app.route("/")
@cross_origin()
def home():
return "Hello World!"
if __name__ == "__main__":
app.run(debug=True)
Explanation:
- @cross_origin() enables CORS only for the specified route.
- Other routes remain unaffected.
- This approach provides better control over API access.
Flask-CORS Configuration Options
Flask-CORS provides several configuration options to customize access rules.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(
app,
origins=["http://localhost:3000"],
methods=["GET", "POST"],
supports_credentials=True
)
Other Configuration Options
| Option | Description |
|---|---|
| origins | Specifies allowed domains. |
| methods | Specifies allowed HTTP methods. |
| allow_headers | Specifies allowed request headers. |
| supports_credentials | Allows cookies and authentication headers. |
| max_age | Sets how long browsers cache preflight requests. |