Skip to content
← cd ../posts
[Developer Tools]5 min read

CORS Debugging: Why curl Works but the Browser Fails

Debug CORS with a working two-origin Node.js example: trace preflight requests, match allowed origins, and verify browser access without weakening security.

Quick answer

curl can succeed while a browser fails because curl does not enforce the browser’s cross-origin response-access policy. Check whether the preflight or the actual response failed, then verify the exact origin, method, headers, and credentials policy. CORS does not replace authentication or authorization.

A browser and an API server connected through a permission gate, with amber inspection and teal data envelopes.

Your shipping quote endpoint returns JSON in curl. The checkout page reports “Failed to fetch.” You restart the API, loosen a firewall rule, and still see the same browser error. The useful next step is to compare the browser's request sequence with the successful command-line request.

This walkthrough builds a tiny local checkout and quote API on different ports. You will deliberately break browser access, inspect the preflight, and restore one exact allowed origin. The quote is a fixed fixture: no orders, payments, or external services are involved.

First separate transport from browser permission

CORS controls whether browser JavaScript can access a cross-origin response. curl does not enforce that browser policy. A successful curl request proves that particular HTTP exchange worked; it does not prove the browser is permitted to read it. Scheme, host, and port define the origin, so our ports 4310 and 4311 are different origins. See MDN's CORS guide.

Record the page URL, API URL, request method, Origin header, requested headers, and any redirect. Use DevTools Network alongside the console. “Failed to fetch” alone also fits network or TLS failures; it is not a diagnosis. Start from the evidence in the API debugging checklist.

Run a two-origin example

Save the following as cors-lab.mjs and run node cors-lab.mjs with a supported Node.js installation. It uses only the built-in HTTP module; no packages or credentials are required. Open exactly http://127.0.0.1:4310, open DevTools Network, and click Send JSON. Do not replace the address with localhost: the explicit allowlist would no longer match. Stop both local servers with Ctrl+C before restarting the example.

javascript
import { createServer } from 'node:http'

const allowedOrigin = 'http://127.0.0.1:4310'
const html = `<!doctype html><meta charset="utf-8">
<title>CORS lab</title><button id="run">Send JSON</button><pre id="out"></pre>
<script>
document.querySelector('#run').onclick = async () => {
  const out = document.querySelector('#out');
  try {
    const response = await fetch('http://127.0.0.1:4311/quote', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sku: 'DEMO-1' })
    });
    out.textContent = response.status + ' ' + await response.text();
  } catch (error) { out.textContent = error.name + ': check DevTools'; }
};
</script>`

createServer((_req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
  res.end(html)
}).listen(4310, '127.0.0.1')

createServer((req, res) => {
  console.log(req.method, req.url, req.headers.origin || '(no Origin)')
  res.setHeader('Cache-Control', 'no-store')
  res.setHeader('Vary', 'Origin')
  // Change ALLOW_CORS to 0 to reproduce the browser failure.
  const allowed = process.env.ALLOW_CORS !== '0' &&
    req.headers.origin === allowedOrigin
  if (allowed) res.setHeader('Access-Control-Allow-Origin', allowedOrigin)
  if (req.url !== '/quote') { res.writeHead(404); res.end(); return }
  if (req.method === 'OPTIONS') {
    const requestedHeaders = String(req.headers['access-control-request-headers'] || '')
      .split(',').map(h => h.trim().toLowerCase()).filter(Boolean)
    if (!allowed || req.headers['access-control-request-method'] !== 'POST' ||
        requestedHeaders.some(h => h !== 'content-type')) {
      res.writeHead(403); res.end(); return
    }
    res.setHeader('Access-Control-Allow-Methods', 'POST')
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
    res.writeHead(204); res.end(); return
  }
  if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
  // Fixed teaching fixture: consumes but does not parse, store, or act on input.
  req.resume()
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ sku: 'DEMO-1', shippingCents: 600 }))
}).listen(4311, '127.0.0.1')

console.log('Open http://127.0.0.1:4310 and click Send JSON. Ctrl+C stops both servers.')

The page should display 200 {"sku":"DEMO-1","shippingCents":600}. In a fresh browser context, the API log shows OPTIONS /quote followed by POST /quote. Our JSON Content-Type triggers a preflight. The successful OPTIONS response permits the method and header; the POST response also supplies Access-Control-Allow-Origin. Allowing only the preflight is insufficient.

The example intentionally returns a fixed quote instead of parsing input. It binds to the loopback interface, has no authentication, and must not be copied wholesale into a public order service. Use your framework's CORS middleware and normal validation, authentication, and authorization for an actual API. Node's HTTP documentation explains the low-level server interface used here.

Break it, then compare the evidence

Stop the server. In a macOS or Linux shell, restart it with ALLOW_CORS=0 node cors-lab.mjs. Open the page in a fresh browser context to avoid reusing a previous preflight permission, then click Send JSON. The page now displays a TypeError message. In this controlled failure, the server answers OPTIONS with 403 and the browser does not send the POST.

Run this independently in a second terminal:

curl -i http://127.0.0.1:4311/quote -H 'Content-Type: application/json' --data '{"sku":"DEMO-1"}'

It still returns the fixed JSON with 200. The server's POST handler is reachable. Our browser exchange failed earlier, at the permission check. curl did not send the same preflight sequence, so its success never tested that part of the application.

Inspect that preflight explicitly:

curl -i -X OPTIONS http://127.0.0.1:4311/quote -H 'Origin: http://127.0.0.1:4310' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: content-type'

With ALLOW_CORS=0 you should get 403. Restart normally and repeat: expect 204, the exact allowed origin, POST in Access-Control-Allow-Methods, and Content-Type in Access-Control-Allow-Headers. Change the Origin port to 9999 and expect 403 again. That negative case verifies the sample did not become an unrestricted origin reflector. Finish with a fresh browser test; inspecting headers in curl alone is not the acceptance test.

Find the layer that returned the response

In a deployed system, compare the response from the public URL with the application log. An OPTIONS request might receive a gateway login redirect, a proxy 404, or a rate-limit response before your route runs. If the application never saw it, changing route code cannot fix that response. Use the HTTP status explorer to interpret the status you actually received.

If OPTIONS succeeds but the actual response fails, inspect that second response. Exercise a successful request and a legitimate application error from the allowed origin. A gateway-generated error without the appropriate CORS policy can hide the useful error body from the browser. Configure each response-producing layer deliberately; keep the same origin restrictions on error paths.

CORS is not authentication or general protection against unwanted writes. Some requests can be sent without preflight, and non-browser clients do not have to obey CORS. Keep authorization and any needed CSRF defenses at the application boundary.

Handle credentials and caching deliberately

For a fetch using credentials: 'include', the server must use a specific allowed origin rather than *, and Access-Control-Allow-Credentials must be true. Preflight itself excludes cross-origin credentials, so an authentication layer that requires a session cookie on OPTIONS can block the browser before the real request. Cookie rules remain a separate condition. These combinations are defined by the Fetch standard.

Our lab does not send credentials. Do not add them just to silence an error. First establish whether the real endpoint is intentionally cookie-authenticated and whether that exact frontend should read its response.

When a server changes its CORS response based on Origin, use Vary: Origin so caches distinguish those responses. Preflight permissions have a separate browser cache; a missing OPTIONS on a repeat request is not automatically a defect. Use a fresh browser context for a clean comparison. The HTTP caching checklist helps separate stale content from stale assumptions about which response you inspected.

Avoid the no-cors detour

Adding mode: 'no-cors' does not make cross-origin JSON readable. It restricts the request and produces an opaque response for this kind of fetch, whose body and headers your script cannot inspect. That cannot satisfy a checkout waiting for a shipping quote. MDN's request-mode reference describes those restrictions.

A checklist for the next incident

  • Capture the exact page origin and final API URL, including scheme and port.
  • Check whether an OPTIONS request failed or the actual response failed.
  • Match the requested method and header names against the server's policy.
  • Verify the allowed origin on the actual response as well as preflight.
  • Trace proxy, redirect, authentication, and error responses to their owner.
  • Test allowed and disallowed origins in a real browser context.
  • Confirm credentials are intentional and keep authorization independent of CORS.
  • Record one failing case, one passing case, and the precise configuration change.

A useful incident note says “the gateway rejected OPTIONS before the quote route ran,” or “the frontend used localhost while the allowlist expected 127.0.0.1.” That is a fix another engineer can verify, instead of a collection of headers added until the console became quiet.

Sources and further reading

These references explain the standards and APIs discussed in this guide. Check the documentation for the versions and services in your environment.

Related Posts

Useful Tools For This Topic

explore_all →