When performing cross-origin requests using jQuery, you may encounter errors related to missing 'Access-Control-Allow-Origin' headers. This occurs when the server has not explicitly allowed cross-origin requests. To resolve this issue in Flask, you can follow these steps:
Install the Flask-CORS extension using pip:
<code class="bash">pip install -U flask-cors</code>
Import the Flask-CORS package and initialize it in your Flask application:
<code class="python">from flask_cors import CORS app = Flask(__name__) cors = CORS(app)</code>
Specify the allowed CORS headers in your Flask configuration:
<code class="python">app.config['CORS_HEADERS'] = 'Content-Type'</code>
Within your request handling methods, explicitly allow cross-origin requests using the @cross_origin() decorator:
<code class="python">@app.route("/") @cross_origin() def helloWorld(): return "Hello, cross-origin-world!"</code>
Once the CORS configuration is in place, you can deploy your Flask application to Heroku.
The above is the detailed content of How to Enable Cross-Origin Resource Sharing (CORS) in Flask Applications?. For more information, please follow other related articles on the PHP Chinese website!