The browser and React · Question 13 of 50

What is CORS, and how do you fix a CORS error?

What they're checking

The same-origin policy, and knowing the fix lives on the server.

The answer

Browsers stop a page from reading responses from another origin (scheme, host and port) unless that server says it is allowed. CORS is how the server says so, with response headers such as Access-Control-Allow-Origin: https://app.example.com.

For requests that are not "simple" (PUT or DELETE, a JSON body, an Authorization header), the browser first sends an OPTIONS preflight, and the server must answer with the methods and headers it allows. The fix is on the API server, or a proxy on your own origin, never in frontend code. CORS protects users in browsers; it does not stop curl or another server from calling your API.

// Express
app.use(cors({ origin: 'https://app.example.com', credentials: true }))

The picture

app.example.com ── OPTIONS (preflight) ─────▶ api.other.com
                ◀── Allow-Origin: app.example.com
                    Allow-Methods: PUT
                ── PUT /orders ──────────────▶
                ◀── 200 + Allow-Origin ─────── the browser lets JS read it
The follow-up they'll ask

Why can't you use * when sending cookies?

Show the answer

With credentials, the browser needs the exact origin in Allow-Origin plus Allow-Credentials: true. A wildcard is refused.

Your progress stays on this device.