CORS Quick Guide

Understand Cross-Origin Resource Sharing and common browser errors.

When to Check CORS First

Check CORS early when a browser request fails but the same API works in curl or Postman. That usually means the backend is reachable, but the browser is blocking access because the origin, headers, credentials, or preflight response do not match.

What CORS Does

CORS allows browsers to permit cross-origin requests when the server explicitly allows them.

Key Response Headers

Key / CodeDescription
Access-Control-Allow-OriginWhich origins are allowed (e.g., https://devref.cc).
Access-Control-Allow-MethodsAllowed methods (GET, POST, etc.).
Access-Control-Allow-HeadersAllowed request headers.
Access-Control-Allow-CredentialsWhether cookies/credentials are allowed.
Access-Control-Expose-HeadersResponse headers accessible to JS.
Access-Control-Max-AgeCache duration for preflight response.

Preflight Requests

Browsers send an OPTIONS request before certain cross-origin calls.

OPTIONS /api/items
Origin: https://devref.cc
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

Common Errors

Key / CodeDescription
CORS blockedMissing or mismatched Allow-Origin header.
Credentials issueAllow-Credentials true but Allow-Origin is * (invalid).
Preflight failedServer does not respond to OPTIONS correctly.

Common CORS Mistakes

The most common mistake is trying to fix CORS only in frontend code. CORS is enforced by the browser and must be allowed by the server response, including correct handling of OPTIONS and consistent headers across success and error responses.

Related

Knowledge is power.