CORS Error — When the Browser Blocks a Request
Troubleshooting / cors-error.html
Cause and fix for the 'blocked by CORS policy' message when calling an API from the frontend.
💬 Symptom: "No 'Access-Control-Allow-Origin' header is present".
For security, browsers block results from a server other than the page's origin by default. This is not a broken server — the server simply did not send the allow header.
Cause
- Frontend (
localhost:5173) and API (localhost:8000) differ in port = different origin. - The response lacks an
Access-Control-Allow-Originheader.
Diagnose
curl -i http://localhost:8000/api/items | grep -i access-control
Fix (FastAPI example)
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_methods=["*"],
allow_headers=["*"],
)
- In production, list real domains instead of
allow_origins=["*"].
Verify the fix
- curl again; seeing
Access-Control-Allow-Originmeans success. - Check response headers in the browser DevTools Network tab.
Sources
- Official docs MDN — CORS — Official docs
- stackoverflow SO 20035101 — Canonical question
Verified date indicates freshness. Check applicability conditions for older material.