How to Enable CORS in Flask
Cross-Origin Resource Sharing (CORS) allows web applications to make requests to servers on different origins (domains, ports, or protocols) than the one on which they were originally loaded. When a client makes a cross-origin request, the server can decide whether to allow the request or not by setting the 'Access-Control-Allow-Origin' header.
To enable CORS in Flask, you can use the 'flask-cors' extension. This extension provides a simple and consistent way to configure CORS for your Flask application.
To install 'flask-cors', use the following command:
pip install -U flask-cors
Once you have installed 'flask-cors', you can configure it for your Flask application by adding the following code to your application:
<code class="python">from flask import Flask from flask_cors import CORS app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' @app.route("/") @cross_origin() def helloWorld(): return "Hello, cross-origin-world!"</code>
The 'CORS_HEADERS' configuration option specifies the allowed request headers. In this example, it allows the 'Content-Type' header, which is the default header used when sending a POST request.
The '@cross_origin()' decorator specifies that the function should allow cross-origin requests. It can be used on individual routes or on the entire application.
By following these steps, you can enable CORS in your Flask application and allow cross-origin requests from other domains.
The above is the detailed content of How to Enable CORS in Flask: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!