CodexBloom - Programming Q&A Platform

Trouble with Configuring Flask-CORS for Python 3.9 and React Frontend in Development

👀 Views: 64 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-06
flask cors react Python

I'm deploying to production and I'm stuck on something that should probably be simple..... I'm facing issues with enabling CORS in my Flask application that serves a React frontend. I'm using Flask 2.0.1 and Flask-CORS 3.9.0, and I want to allow specific origins during development. I've set up my Flask app like this: ```python from flask import Flask from flask_cors import CORS app = Flask(__name__) # Allow CORS for specific origins CORS(app, resources={r"/*": {"origins": ["http://localhost:3000"]}}) @app.route('/api/data') def get_data(): return {'data': 'Hello from Flask!'} if __name__ == '__main__': app.run(debug=True) ``` However, when I try to fetch data from my React app using: ```javascript fetch('http://localhost:5000/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` I get a CORS error in the browser console: `Access to fetch at 'http://localhost:5000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I've double-checked that my Flask app is running on port 5000 and my React app on port 3000. I've also tried various configurations for Flask-CORS, but nothing seems to work. I've ensured that `flask_cors` is properly installed in my environment. What am I missing here? Has anyone else encountered this? Could someone point me to the right documentation? This is my first time working with Python stable. Am I missing something obvious?