Learn CORSErrorsTesterFrameworksQuizSearch

What Is CORS? A Browser-to-API Explanation

By Ankit Jain · Updated

Understand why an API can work in curl but fail in a browser, and how a server grants cross-origin response access.

CORS stands for Cross-Origin Resource Sharing. It is the response-header protocol a server uses to grant browser JavaScript access to a response from another origin.

Start with one request

Your page runs at https://app.example.com. It calls https://api.example.com/profile. The host differs, so this is a cross-origin request. The API can grant the page access by returning:

Access-Control-Allow-Origin: https://app.example.com

Without valid permission, the browser keeps the response unavailable to your JavaScript. A simple request can still reach the API and change server state. For a request that requires preflight, the browser checks permission before sending the actual request.

Three questions to keep separate

  1. Did the request reach the server? Check Network and server logs.
  2. May JavaScript read the response? Check CORS permissions on OPTIONS when required and on the actual response.
  3. Did the operation succeed? Check authentication, HTTP status, and application data.

An HTTP 200 without origin permission can fail CORS. An HTTP 401 with valid permission can be readable. CORS does not log you in or replace authorization and CSRF protection.

Who changes what?

The frontend controls the endpoint URL, method, headers, and credentials mode. The browser sends Origin and any preflight. The API or gateway controls response permission. If you do not control the API, ask its owner for a supported browser integration or use an authenticated backend you control; adding permission headers to fetch does not work.

Continue with origins, then simple requests and preflight.

References