Home >Backend Development >Python Tutorial >How to Implement Cross-Origin Resource Sharing (CORS) in Flask: A Step-by-Step Guide
CORS in Flask: A Step-by-Step Guide to Enabling Cross-Origin Requests
Cross-Origin Resource Sharing (CORS) is an essential mechanism for allowing cross-domain requests in web applications. Flask, a popular Python-based web framework, provides built-in support for CORS, making it straightforward to enable cross-origin access.
Enabling CORS in Flask
If you're experiencing the "XMLHttpRequest cannot load" error due to missing CORS headers, follow these steps:
Install flask-cors:
<code class="shell">pip install Flask-CORS</code>
Import CORS in Flask:
<code class="python">from flask_cors import CORS</code>
Initialize CORS Object:
<code class="python">cors = CORS(app)</code>
Configure CORS Headers:
Update the CORS configuration to specify the headers that will be allowed for cross-origin requests. By default, Flask-CORS allows only the "Content-Type" header. You can expand this to include additional headers as needed, such as "Authorization."
<code class="python">app.config['CORS_HEADERS'] = 'Content-Type, Authorization'</code>
Apply CORS to a Specific Route:
Wrap your route with the @cross_origin() decorator to enable CORS for that specific route.
<code class="python">@app.route("/") @cross_origin() def my_route(): ...</code>
Alternatively, you can apply the decorator globally to all routes:
<code class="python">@app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') return response</code>
With these steps in place, Flask will automatically add the necessary CORS headers to your responses, allowing cross-origin requests from other domains.
Additional Notes
The above is the detailed content of How to Implement Cross-Origin Resource Sharing (CORS) in Flask: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!