Fix CORSError: Access to XMLHttpRequest at 'http://localhost:5000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy in Flask
This error occurs when a browser blocks a cross-origin request because the Flask server does not include the required CORS headers. Fix it by installing and configuring Flask-CORS with the correct allowed origins, or by manually adding Access-Control-Allow-Origin headers to your responses using an after_request handler.
Reading the Stack Trace
Here's what each line means:
- No 'Access-Control-Allow-Origin' header is present on the requested resource.: The browser's preflight check found no CORS headers in the response, so it blocked the frontend request.
- "OPTIONS /api/data HTTP/1.1" 405 -: The browser sent a preflight OPTIONS request but Flask returned 405 Method Not Allowed because no OPTIONS handler is registered.
- File "/app/app/routes.py", line 10, in get_data: The actual route handler works fine — the issue is the missing CORS headers, not the application logic.
Common Causes
1. Flask-CORS not installed or configured
The Flask app does not include the Flask-CORS extension, so no CORS headers are added to responses.
from flask import Flask, jsonify
app = Flask(__name__)
# No CORS configuration
@app.route('/api/data')
def get_data():
return jsonify({'items': []})
2. Origins not matching
Flask-CORS is installed but configured with the wrong allowed origin, so the frontend domain is still blocked.
from flask_cors import CORS
CORS(app, origins=['http://example.com']) # frontend is on localhost:3000
3. Credentials not allowed
The frontend sends cookies or auth headers but CORS is not configured to support credentials.
CORS(app, origins='*') # wildcard does not work with credentials
# Frontend: fetch(url, { credentials: 'include' })
The Fix
Install flask-cors and initialize CORS with the specific frontend origin. Setting supports_credentials=True allows cookies and auth headers. Avoid using origins='*' in production as it disables credential support and weakens security.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/data')
def get_data():
return jsonify({'items': []})
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origins=['http://localhost:3000'], supports_credentials=True)
@app.route('/api/data')
def get_data():
return jsonify({'items': []})
Testing the Fix
import pytest
from app import create_app
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
return app.test_client()
def test_cors_headers_present(client):
response = client.get('/api/data')
assert 'Access-Control-Allow-Origin' in response.headers
def test_preflight_options_returns_200(client):
response = client.options('/api/data', headers={
'Origin': 'http://localhost:3000',
'Access-Control-Request-Method': 'GET'
})
assert response.status_code == 200
def test_data_endpoint_returns_json(client):
response = client.get('/api/data')
assert response.status_code == 200
assert response.content_type == 'application/json'
Run your tests:
pytest tests/ -v
Pushing Through CI/CD
git checkout -b fix/flask-cors-headers,git add app/__init__.py requirements.txt,git commit -m "fix: add Flask-CORS to allow cross-origin requests",git push origin fix/flask-cors-headers
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- run: pip install -r requirements.txt
- run: pytest tests/ -v --tb=short
- run: flake8 app/
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run pytest locally to confirm CORS headers are present on API responses.
- Open a pull request with the Flask-CORS configuration.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the frontend can reach the API in staging.
Frequently Asked Questions
BugStack verifies CORS headers are present on all API endpoints, tests preflight OPTIONS requests, and confirms credentials flow correctly before marking it safe.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
No. Wildcard origins disable credential support and allow any domain to call your API. Always specify exact allowed origins in production.
CORS is a browser security feature. API tools like curl or Postman do not enforce CORS, so the same request works fine outside the browser.