📌  相关文章
📜  flask cors policy no 'access-control-allow-origin' - Python (1)

📅  最后修改于: 2023-12-03 15:00:46.709000             🧑  作者: Mango

Flask CORS Policy error: no 'Access-Control-Allow-Origin'


When working with Flask, you may encounter an error similar to the following:

Failed to load http://localhost:5000/api: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This error occurs when the server handling the request doesn't specify its CORS policy. CORS stands for "Cross-Origin Resource Sharing" and is a security feature implemented in most modern browsers to prevent malicious requests from different origins.

To fix this error, you need to add the flask-cors extension to your Flask app:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# your Flask routes here...

This tells Flask to handle CORS requests by adding the Access-Control-Allow-Origin header to the response.

If you want to restrict CORS requests to certain origins, you can pass a list of allowed origins to the origins parameter when initializing the CORS extension:

CORS(app, origins=['http://localhost:3000', 'https://example.com'])

Note that you should only allow origins that you trust, to prevent unauthorized requests.

In conclusion, adding the flask-cors extension to your Flask app is the recommended solution to fix the no Access-Control-Allow-Origin error in Python when working with CORS requests.