How to Enable Cross-Origin Requests (CORS) in Flask?

Patricia Arquette
Release: 2024-10-30 20:49:30
Original
367 people have browsed it

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>
Copy after login

Configure the CORS headers:

<code class="python">app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template