📌  相关文章
📜  python flask access-control-allow-origin - Python (1)

📅  最后修改于: 2023-12-03 14:45:57.957000             🧑  作者: Mango

Python Flask Access-Control-Allow-Origin

If you are building a web application using Flask, you may encounter an issue where a web page within a different domain tries to make a request to your Flask API, and the browser blocks the request due to the Same-origin policy. This is where the "Access-Control-Allow-Origin" header comes in to play.

What is Access-Control-Allow-Origin?

Access-Control-Allow-Origin is a response header that your Flask API can return to tell the browser that the request is allowed from a different domain. When a web page tries to make an HTTP request to a different domain, the browser will first send a preflight request (HTTP OPTIONS method) to check if the server allows the request. The server can respond with the Access-Control-Allow-Origin header to indicate if the request is allowed or denied.

How to set Access-Control-Allow-Origin in Flask?

To set the Access-Control-Allow-Origin header in Flask, you can use the Flask-CORS module which provides a simple way to enable CORS in your Flask application.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/api')
def api():
    return {'message': 'Hello World!'}

In this example, we have imported the Flask and Flask-CORS modules, created a new Flask app, enabled CORS using the CORS() function, and defined a simple API route that returns a JSON message.

When a web page tries to make a request to our API endpoint, the browser will first send a preflight request to check if the server allows the request. If the server allows the request, the browser will then make the actual request and receive the response from the server.

Conclusion

In summary, the Access-Control-Allow-Origin header is an important header that your Flask API can return to enable cross-domain requests. By using the Flask-CORS module, you can easily enable CORS in your Flask application and provide a better user experience for your web application.