Short answer: A CORS error means the browser blocked your page from reading a response from another origin because the server did not send the right headers. Fix it on the server: return Access-Control-Allow-Origin with your site’s origin, answer OPTIONS preflight requests with allowed methods and headers, and make sure errors and redirects carry the same headers.

Key takeaways

  • Browsers apply the same-origin policy: a script on one origin cannot read responses from another origin unless that server allows it.
  • The cors middleware handles preflights and headers.
  • FastAPI and Starlette ship a CORS middleware, documented in the FastAPI CORS tutorial :
  • If nginx sits in front of an API you cannot change, add the headers there.

I build frontends and APIs for clients, and CORS is the error that wastes the most time for developers who meet it for the first time, mostly because people try to fix it in the browser code. This guide explains what the browser is actually checking, how to find the real cause in DevTools, and the correct configuration for Express, FastAPI, nginx and the Vite dev server.

How a CORS error happens and how to fix it: browser request, preflight, server headers, allowed response
Request flow behind a CORS error: the page on one origin, the OPTIONS preflight, the API response headers and the browser decision.

From my own work: When someone shows me a CORS error, my first question is: what is the status code of the failing request in the Network tab? Surprisingly often it is a 500 or a 404, and the CORS message is just a side effect because error responses skip the middleware that adds the headers. Fix the error and the CORS message disappears.

What a CORS error actually means

Browsers apply the same-origin policy: a script on one origin cannot read responses from another origin unless that server allows it. An origin is the combination of scheme, host and port, so https://app.example.com, https://api.example.com and http://localhost:5173 are all different origins. Cross-Origin Resource Sharing is the protocol, defined in the Fetch standard, that lets the server opt in. The typical message looks like this:

Access to fetch at 'https://api.example.com/orders' from origin 'https://app.example.com'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Two points cause most confusion. First, the request often reached the server and ran; the browser only hides the response from your JavaScript. Second, tools like curl and Postman never show CORS errors because only browsers enforce CORS. The MDN CORS guide is the best general reference.

Simple requests vs preflight requests

Request When it happens What the server needs
Simple request GET, HEAD or POST with only basic headers and a form or plain text content type Access-Control-Allow-Origin on the response
Preflighted request PUT, PATCH or DELETE, JSON content type, an Authorization header or other custom headers A successful OPTIONS response with allow-origin, allow-methods and allow-headers, then allow-origin on the real response
Credentialed request Cookies or HTTP authentication with credentials: "include" The exact origin, not *, plus Access-Control-Allow-Credentials: true

Sending JSON with Content-Type: application/json or a bearer token always triggers a preflight, which is why an API that works for GET suddenly fails for POST. This is the exchange the browser expects:

# What the browser sends before the real request (preflight)
OPTIONS /orders HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization, content-type

# What the server must answer
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600
Vary: Origin

How to debug a CORS error step by step

  1. Open DevTools, Network tab, and reproduce the error with the console open.
  2. Find the failing request. If there is an OPTIONS request before it, inspect that first.
  3. Check the status code. A 404, 405, 500 or 3xx on the preflight or request is the real problem.
  4. Check the response headers for Access-Control-Allow-Origin and compare its value with the page origin character by character, including the scheme and port.
  5. Reproduce with curl to see exactly what the server returns, without browser caching:
# Simulate the preflight from the command line
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"

If the OPTIONS request returns 401 because your authentication middleware runs first, allow OPTIONS through without a token. Browsers never send credentials on a preflight.

From my own work: A sneaky case I hit on a client project: the API redirected http to https, and the preflight followed the redirect. Browsers do not accept a redirect on a preflight, so every POST failed with a CORS message. Calling the https URL directly in the frontend fixed it without touching the server.

Fix the CORS error in Express (Node.js)

The cors middleware handles preflights and headers. Use an allowlist rather than reflecting any origin:

// Express with the cors package
import express from "express";
import cors from "cors";

const app = express();
const allowed = ["https://app.example.com", "http://localhost:5173"];

app.use(cors({
  origin(origin, cb) {
    // allow server-to-server calls with no Origin header, and listed origins
    if (!origin || allowed.includes(origin)) return cb(null, true);
    cb(new Error("Origin not allowed"));
  },
  credentials: true,                 // only if you use cookies
  methods: ["GET", "POST", "PUT", "DELETE"],
  allowedHeaders: ["Authorization", "Content-Type"],
  maxAge: 600,
}));

Register it before your routes and before authentication middleware, so OPTIONS requests and error responses also get the headers. If your fetch calls use timeouts and retries, my guides to fetch timeouts with AbortController and retries with exponential backoff pair well with this setup.

Fix it in FastAPI (Python)

FastAPI and Starlette ship a CORS middleware, documented in the FastAPI CORS tutorial:

# FastAPI
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com", "http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

Django projects typically use the django-cors-headers package, and Laravel has CORS settings in config/cors.php. The principle is the same everywhere: list the origins, methods and headers explicitly.

Fix it in nginx

If nginx sits in front of an API you cannot change, add the headers there. The always parameter matters, because without it add_header skips error responses, as documented in the nginx headers module:

# nginx in front of an API: one allowed origin
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, DELETE" always;
        add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
        add_header Access-Control-Max-Age 600 always;
        add_header Vary Origin always;
        return 204;
    }
    add_header Access-Control-Allow-Origin "https://app.example.com" always;
    add_header Vary Origin always;
    proxy_pass http://127.0.0.1:8000;
}

Do not add CORS headers in both nginx and the application, or the browser sees duplicate values and rejects them. For other response headers on the same server, see my guide to nginx security headers.

Cookies and credentials

// Client: send cookies cross-origin
fetch("https://api.example.com/me", { credentials: "include" });

// Server must then answer with a specific origin (not *) and:
// Access-Control-Allow-Origin: https://app.example.com
// Access-Control-Allow-Credentials: true

With credentials, the wildcard origin is not allowed and the server must return Vary: Origin if it echoes different allowed origins, so caches do not serve one origin’s headers to another. Cross-site cookies also need SameSite=None; Secure, and some browsers restrict third-party cookies, so for a new project put the frontend and API on the same site, such as app.example.com and api.example.com, or use bearer tokens.

Avoid CORS in development with a proxy

During local development the page runs on localhost:5173 and the API on localhost:8000, which are different origins. Instead of opening CORS wide, let the dev server proxy API calls so the browser only talks to one origin, as described in the Vite server.proxy docs:

// vite.config.js: in development, call /api on the same origin
import { defineConfig } from "vite";
export default defineConfig({
  server: {
    proxy: {
      "/api": { target: "http://localhost:8000", changeOrigin: true },
    },
  },
});

Your frontend then calls /api/orders and works the same way in production when nginx routes /api to the backend on the same domain.

From my own work: On most projects I now serve the API under the same domain as the app, for example example.com/api, through the reverse proxy. CORS disappears completely, cookies just work, and there is one less thing to break when someone adds a new header.

Fixes that are not fixes

  • mode: "no-cors": the request is sent but the response is opaque, so your code cannot read the status or body.
  • Browser extensions that disable CORS: they hide the problem on your machine only; real users still get the error.
  • Access-Control-Allow-Origin: * everywhere: fine for truly public, read-only data, wrong for anything authenticated.
  • Reflecting any Origin with credentials: this lets any website make authenticated requests as your users. Use an allowlist.
  • Public CORS proxies: they see your traffic and tokens and can disappear at any time.

CORS error checklist

  • Read the status code of the request and its preflight first.
  • Fix 404, 500, 401 on OPTIONS and redirects before touching CORS headers.
  • Return the exact origin, including scheme and port.
  • Answer OPTIONS with allowed methods and headers, without requiring auth.
  • Add headers to error responses too (always in nginx).
  • Set the headers in one layer only, app or proxy.
  • With cookies: specific origin, Allow-Credentials true, Vary: Origin, SameSite=None; Secure.
  • Use a dev proxy locally and a same-origin route in production where possible.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What causes a CORS error?

A CORS error happens when a web page calls an API on a different origin, meaning a different scheme, domain or port, and the API’s response does not include headers that allow that origin. The browser then blocks the page from reading the response.

How do I fix No Access-Control-Allow-Origin header is present?

Configure the API server, not the frontend, to return Access-Control-Allow-Origin with your site’s origin, and to answer OPTIONS preflight requests with the allowed methods and headers. Also check the request is not failing with a 404, 500 or redirect that lacks the headers.

Can I fix CORS on the frontend?

Not for a server you do not control. The browser enforces the server’s CORS headers. In development you can avoid CORS with a dev server proxy so the browser calls the same origin, and in production you can route the API through your own domain or backend.

Why does mode no-cors not fix the error?

mode: no-cors makes the request but returns an opaque response that JavaScript cannot read, so your code gets no status or body. It only suits fire-and-forget requests, not API calls whose data you need.

Why can’t I use Access-Control-Allow-Origin * with cookies?

For requests with credentials such as cookies, the Fetch standard requires the server to return the exact requesting origin and Access-Control-Allow-Credentials: true. A wildcard origin is rejected by the browser in that case.

Why does Postman work but the browser shows a CORS error?

Postman, curl and server-side code do not enforce CORS; only browsers do. The API works, but its responses lack the headers that let a browser page on another origin read them.

About the author. Saizul Amin is a web developer and technical SEO consultant from Dhaka who manages Ubuntu VPS servers, nginx, Cloudflare, WordPress and n8n in production for his own and client sites. Every command in these guides is one he runs himself; his open-source tools are on GitHub and his client work is at saizul.com.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.