0
0
Flaskframework~5 mins

CORS configuration with Flask-CORS

Choose your learning style9 modes available
Introduction

CORS lets your web app share resources safely with other websites. Flask-CORS helps you set this up easily in Flask apps.

You want your Flask API to be used by a web page hosted on a different domain.
You build a frontend app on one server and backend API on another and want them to talk.
You want to allow only specific websites to access your Flask app resources.
You want to avoid browser errors about blocked cross-site requests.
You want to control which HTTP methods and headers are allowed from other sites.
Syntax
Flask
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})

Use CORS(app) to enable CORS for all routes and origins.

Use resources to limit CORS to certain URL patterns and origins to specify allowed domains.

Examples
This allows any website to access your Flask app resources.
Flask
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Allow all origins for all routes
Only requests from http://myfrontend.com to URLs starting with /api/ are allowed.
Flask
CORS(app, resources={r"/api/*": {"origins": "http://myfrontend.com"}})
Allows cookies and credentials to be sent with cross-origin requests.
Flask
CORS(app, supports_credentials=True)
Sample Program

This Flask app allows only requests from http://frontend.example.com to access the /data route. Other origins will be blocked by the browser.

Flask
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
# Allow CORS only for frontend.example.com on /data route
CORS(app, resources={r"/data/*": {"origins": "http://frontend.example.com"}})

@app.route('/data')
def data():
    return jsonify({'message': 'Hello from Flask!'})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Browsers enforce CORS, so server must send correct headers for cross-origin requests to work.

Flask-CORS adds these headers automatically based on your config.

Always restrict origins in production to avoid security risks.

Summary

CORS controls which websites can access your Flask app resources.

Flask-CORS makes it easy to add CORS headers to your Flask routes.

Configure origins and routes carefully to keep your app safe and accessible.