Home > Article > Backend Development > How to Enable Cross-Origin Requests (CORS) in Flask?
How to Resolve Cross-Origin Request Issues in Flask
When attempting cross-origin requests with jQuery, you may encounter the error: "'XMLHttpRequest cannot load... No 'Access-Control-Allow-Origin' header is present on the requested resource.'" However, by enabling CORS in Flask, this issue can be resolved. Here's how:
In your Flask application, add the necessary dependencies:
<code class="python">from flask import Flask from flask_cors import CORS, cross_origin</code>
Configure the CORS headers:
<code class="python">app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type'</code>
For each route where you want to enable CORS, use the @cross_origin decorator:
<code class="python">@app.route("/") @cross_origin() def helloWorld(): return "Hello, cross-origin-world!"</code>
This method will enable CORS for the specified route. Remember to specify the desired HTTP methods in the cross_origin decorator if necessary. By following these steps, you can effortlessly resolve CORS-related issues in your Flask application.
The above is the detailed content of How to Enable Cross-Origin Requests (CORS) in Flask?. For more information, please follow other related articles on the PHP Chinese website!