Full Byte Developer.

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

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

text
Access-Control-Allow-Origin: https://your-site.example

Use 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:

text
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type

3. Handle credentials

If you use credentials: 'include' for cookies or auth:

text
Access-Control-Allow-Credentials: true

And never Access-Control-Allow-Origin: * with credentials.

Check it from your terminal

bash
curl -i -H "Origin: https://your-site.example" https://your-api.example/api

Look 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

By Full Byte Developer

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

  1. MDN: CORS errorsdeveloper.mozilla.org
  2. MDN: CORSMissingAllowOrigindeveloper.mozilla.org
  3. MDN: RequestInitdeveloper.mozilla.org

Next in this stack