CORS error? Read the console, fix the server
Data will not load and your AI keeps editing the frontend? The fix usually lives on the server.
Published here · 4 sources · Resume reading
Data still will not load and your AI keeps editing the frontend? Read the console line first. If it says "blocked by CORS policy", the fix usually lives on the server.
The problem
Two local servers, Chrome 156. The API answered 200 with the data. The browser still blocked it, because the response had no Access-Control-Allow-Origin header. The page's JavaScript only got "TypeError: Failed to fetch". The real reason was in the console.
The fix (server response headers)
1. Allow the origin
Access-Control-Allow-Origin: https://your-site.exampleUse your site's exact origin. If you echo the request Origin instead, also send Vary: Origin.
2. Answer the OPTIONS preflight
If your request sends JSON or custom headers:
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type3. Handle credentials
If you use credentials: 'include' for cookies or auth:
Access-Control-Allow-Credentials: trueAnd never Access-Control-Allow-Origin: * with credentials.
Check it from your terminal
curl -i -H "Origin: https://your-site.example" https://your-api.example/apiLook for the Access-Control-Allow-Origin line in the response.
The no-cors trap
It hides the error, but the response is opaque: status 0, empty body. Your code cannot read the data.
Send this to the friend whose AI keeps editing the frontend to fix a CORS error.
Keep this guide
Filed under Dev tools
Questions about this guide
Why not use mode: no-cors?
It hides the error, but the response is opaque: status 0, empty body. Your code cannot read the data.
Can I use Access-Control-Allow-Origin: * with credentials?
No. If you need cookies or auth with credentials: include, also set Access-Control-Allow-Credentials: true, and never use the wildcard.
Sources
- MDN: CORS errorsdeveloper.mozilla.org
- MDN: CORSMissingAllowOrigindeveloper.mozilla.org
- MDN: Cross-Origin Resource Sharingdeveloper.mozilla.org
- MDN: RequestInitdeveloper.mozilla.org