Your endpoint returns perfect JSON in Postman, curl, or Insomnia, yet the same request from JavaScript produces a frustrating CORS error. The API may be healthy; the difference is that browsers enforce cross-origin security rules that standalone API clients do not. Fixing the problem requires inspecting the browser’s preflight and the server’s response—not changing the frontend until the warning disappears.
Why an API works in Postman but not the browser
Browser code operates under the same-origin policy. Two URLs have the same origin only when their scheme, host, and port match. For example, https://app.example.com and https://api.example.com are different origins because their hosts differ. Changing from HTTP to HTTPS or from port 3000 to 8000 also creates a cross-origin request.
The same-origin policy prevents a malicious page from freely reading data from another site where a visitor may be signed in. Cross-Origin Resource Sharing, or CORS, is the controlled exception: the API sends response headers indicating which external origins may read its responses.
Postman and curl are not browser page contexts, so they do not enforce the browser’s CORS policy. A 200 response in either tool proves that the route is reachable, but it does not prove that the response grants access to your frontend. This is the central reason an API works in Postman but not browser JavaScript.
CORS is enforced by the browser, but permission comes from the server. The browser can send a request successfully and still prevent JavaScript from reading the response when the required headers are absent or invalid.
Simple requests and the CORS preflight request
Some cross-origin requests are considered “simple.” A typical GET using only safelisted headers may be sent immediately, although the browser still checks the response for a valid Access-Control-Allow-Origin value.
Other requests require permission in advance. Before sending the real request, the browser issues an OPTIONS request called a CORS preflight request. Preflight commonly occurs when an application:
- Uses PUT, PATCH, DELETE, or another non-safelisted method.
- Sends an
Authorizationheader. - Uses
Content-Type: application/json. - Adds custom headers such as
X-Request-ID.
The preflight includes Origin, Access-Control-Request-Method, and, when needed, Access-Control-Request-Headers. The API must answer with an acceptable status and matching CORS headers. Only then does the browser send the intended request. An OPTIONS request error therefore often means your controller was never reached.
What the main CORS response headers mean
Access-Control-Allow-Origin
Access-Control-Allow-Origin must contain either one matching origin or * where a wildcard is permitted. It cannot contain a comma-separated list. If the server selects an origin dynamically from an allowlist, it should also return Vary: Origin so caches do not reuse one origin’s response for another.
Allowed methods and headers
Access-Control-Allow-Methods tells the preflight which methods are permitted. Access-Control-Allow-Headers approves requested headers such as Authorization and Content-Type. These are response headers supplied by the API; adding them to the frontend request is ineffective and can itself trigger preflight.
Credentials and CORS
When JavaScript uses credentials: 'include', or an equivalent client option, the response must include Access-Control-Allow-Credentials: true. A credentialed response cannot use Access-Control-Allow-Origin: *; it must name the requesting origin explicitly.
CORS permission does not guarantee that cookies will be sent. Cookie attributes such as SameSite, Secure, domain, and path still apply, while modern browser privacy controls may restrict third-party cookies independently of CORS.
Common reasons CORS configuration fails
- Missing headers: The successful API response—or an error response generated earlier—does not include the required CORS headers.
- Incorrect origin: The allowlist contains the wrong protocol, hostname, port, or a trailing path. An origin never includes a URL path.
- Rejected OPTIONS requests: The router, web server, firewall, or middleware responds with 404, 405, or 403 before CORS handling runs.
- Authentication runs first: Middleware challenges the unauthenticated preflight with 401 or redirects it to a login page with 302. A preflight does not normally contain the application’s authorization credentials.
- Preflight redirects: HTTP-to-HTTPS redirects, trailing-slash normalization, and login redirects can cause a CORS redirect error. Redirect handling varies by request details, and the redirected endpoint must also pass CORS checks. Point the frontend directly at the final HTTPS URL instead.
- Wildcard with credentials: Combining a wildcard origin with credentialed requests is invalid in browsers.
- Proxy or CDN interference: A reverse proxy may consume OPTIONS, strip headers, cache a response without considering
Origin, or add a secondAccess-Control-Allow-Originheader. Duplicate values are not a valid substitute for one correct value.
Also inspect failures such as 500 and 429 responses. If CORS headers appear only on successful responses, the console may report a CORS policy error that hides the underlying server exception.
Diagnosing CORS in Chrome DevTools and curl
Open Chrome DevTools, select Network, reproduce the request, and filter for the endpoint or OPTIONS. Inspect the preflight before the main request. Confirm its Request URL, Origin, requested method, and requested headers. Then check the response status and every Access-Control-Allow-* header.
If no main request follows, the preflight failed. If the main request appears but JavaScript cannot read it, inspect that response too. The Console often describes the failed check, but the Network panel reveals the actual status, redirect, and headers.
Use curl to simulate a preflight rather than merely calling the route:
curl -i -X OPTIONS 'https://api.example.com/orders' -H 'Origin: https://app.example.com' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: authorization,content-type'The response should approve that origin, POST, and both requested headers. Curl displays what the server returns but never enforces CORS itself. Compare results from the public URL and the origin server to identify CDN or reverse-proxy changes. The MDN CORS guide and the WHATWG Fetch standard provide authoritative details on browser behavior.
Practical server configuration examples
Laravel
Configure Laravel’s CORS settings rather than adding headers in controllers. Ensure CORS middleware runs before authentication and that the route pattern covers the API. Publish the CORS configuration first if it is not present in your Laravel installation.
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'allowed_origins' => ['https://app.example.com'],
'allowed_headers' => ['Content-Type', 'Authorization', 'X-CSRF-TOKEN'],
'exposed_headers' => [],
'max_age' => 600,
'supports_credentials' => true,
];Clear cached configuration after deployment when values have changed. For cookie-based authentication, align CORS with Laravel’s stateful-domain, session, CSRF, and cookie settings.
Plain PHP
Send CORS headers before output and terminate a valid preflight before authentication:
<?php
$allowed = ['https://app.example.com'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowed, true)) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Vary: Origin');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(in_array($origin, $allowed, true) ? 204 : 403);
exit;
}Never reflect an arbitrary Origin while allowing credentials. Validate it against an exact allowlist.
Node.js and Express
The maintained cors middleware can handle preflight globally when registered before routes and authentication:
import cors from 'cors';
app.use(cors({
origin: 'https://app.example.com',
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 600
}));
app.use('/api', apiRouter);For multiple environments, use a callback that compares the supplied origin with a server-side allowlist. Do not return every origin automatically.
Apache and Nginx
For one trusted frontend, Apache can add headers consistently and answer preflight before application authentication:
RewriteEngine On
RewriteCond %{REQUEST_METHOD} =OPTIONS
RewriteRule ^ - [R=204,L]
Header always set Access-Control-Allow-Origin 'https://app.example.com'
Header always set Access-Control-Allow-Methods 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
Header always set Access-Control-Allow-Headers 'Authorization, Content-Type'
Header always set Access-Control-Allow-Credentials 'true'A comparable Nginx API location is:
location /api/ {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin https://app.example.com always;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, PATCH, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Authorization, Content-Type' always;
add_header Access-Control-Allow-Credentials true always;
return 204;
}
add_header Access-Control-Allow-Origin https://app.example.com always;
add_header Access-Control-Allow-Credentials true always;
proxy_pass http://api_upstream;
}Keep responsibility in one layer where possible. If both the application and proxy add CORS headers, conflicting or duplicate values can break an otherwise correct response.
Two fixes that do not solve the problem
Do not add Access-Control-Allow-Origin to Axios or Fetch request headers. It is a server response header, not a permission the client grants itself. Doing so may create an additional non-safelisted header and trigger preflight.
Disabling browser security, installing a permissive extension, or launching Chrome with security flags is useful only for isolated testing. It neither fixes production users nor protects their data. A development proxy can be convenient locally, but production still needs intentional frontend backend integration and secure server-side policy.
Secure CORS troubleshooting checklist
- Record the frontend’s exact scheme, host, and port.
- Inspect OPTIONS and the real request in DevTools.
- Make OPTIONS bypass login redirects and authentication challenges.
- Return one exact allowed origin; use
Vary: Originfor dynamic selection. - Approve only required methods and request headers.
- Never combine credentialed requests with a wildcard origin.
- Include CORS headers on error responses as well as successes.
- Remove redirects by calling the final HTTPS API URL.
- Compare origin-server and CDN responses for stripped, cached, or duplicated headers.
- Retest with both a simulated curl preflight and the real browser request.
Frequently asked questions
Is CORS a server error or a browser error?
The browser reports and enforces it, but the cause is usually a server, middleware, proxy, or CDN response that does not grant the required cross-origin access. Postman will not perform that enforcement.
Why does my GET request have a CORS error without an OPTIONS request?
A simple GET may not need preflight. The browser sends it directly, then blocks JavaScript from reading the response if Access-Control-Allow-Origin is missing or incorrect.
Can I use a wildcard origin for a public API?
Yes, when the resource is genuinely public and the request does not use credentials. Use an explicit allowlist for private data, cookies, client certificates, or credentialed browser requests.
Does fixing CORS secure an API?
No. CORS controls which browser origins may read responses; it is not authentication or authorization. Non-browser clients can still call the API, so every endpoint must independently validate identity, permissions, input, and rate limits.