python flask access-control-allow-origin

  1. Import the necessary modules:
from flask import Flask, jsonify
  1. Create a Flask application:
app = Flask(__name__)
  1. Define a route with a sample endpoint that returns a JSON response:
def sample_endpoint():
    data = {'message': 'Hello, this is a sample endpoint!'}
    return jsonify(data)
  1. Enable CORS (Cross-Origin Resource Sharing) by using the after_request decorator to modify response headers:
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'  # Allow requests from any origin
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE'  # Specify allowed HTTP methods
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'  # Specify allowed headers
    return response
  1. Run the Flask application:
if __name__ == '__main__':
  1. Optionally, you can specify the host and port when running the application:, host='', port=5000)

Note: This example provides a basic structure for a Flask application with CORS support. Adjust the route, endpoint, and CORS headers according to your specific requirements.