You call your API from a React, Vue or plain JavaScript app, and the browser console answers with an error like this:

Access to fetch at 'http://localhost:3000/api/users' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The same request works in Postman or curl, and the API may even return 200, yet your code never receives the response. This guide explains why the browser blocks it, how to find the missing header and how to fix it in Express, Flask, Django, Nginx, PHP and Apache.

I tested every configuration below by sending real requests with an Origin header and reading the response headers. The versions were Express 5.3 with cors 2.8, Flask 3.1 with Flask-CORS 6.0, Django 6.1 with django-cors-headers 4.9, Nginx 1.24, Apache 2.4.58, PHP 8.3 and Vite 8.3. I could not run a browser, so the wording of the browser messages comes from documentation and experience. Firefox and Safari word them differently, but the cause is the same.

What is CORS, and why does the browser block the request?

Browsers apply the same-origin policy: a page may read responses only from its own origin. An origin is the combination of scheme, host and port, so these pairs are different origins:

  • http://localhost:5173 and http://localhost:3000 differ in the port.
  • https://example.com and http://example.com differ in the scheme.
  • https://example.com and https://api.example.com differ in the host.

CORS (Cross-Origin Resource Sharing) is the opt-in that relaxes this rule. The server sends headers such as Access-Control-Allow-Origin to say which origins may read its responses. Two facts explain most confusion:

  • The browser enforces it, not the server. In my tests, a server without any CORS configuration answered a request that carried a foreign Origin header with 200 OK and the data. The browser then keeps that response away from your script. That is why curl and Postman show no problem.
  • CORS is not access control. The request still reaches your server and runs. CORS only decides whether a page can read the answer.

Simple requests and preflight requests

A plain GET or POST with ordinary headers is sent directly. Anything else triggers a preflight: a PUT, PATCH or DELETE request, a custom header such as Authorization, or a JSON body with Content-Type: application/json. Before the real request, the browser sends an OPTIONS request that asks permission, with the headers Access-Control-Request-Method and Access-Control-Request-Headers. If the answer to that preflight does not contain the right headers, the real request is never sent.

Why the Access-Control-Allow-Origin header is missing

  • The server sends no CORS headers at all. This is the default for most frameworks and servers.
  • The origin is not on your allowlist. The match must be exact. A browser sends http://localhost:5173 without a trailing slash, so an allowlist entry written as http://localhost:5173/ never matches. I tested this with the Express cors package. The scheme, the port and www versus non-www matter as well.
  • Authentication runs before CORS. A preflight carries no credentials. When an auth middleware sits in front of the CORS middleware, the preflight gets a 401 with no CORS headers, which I confirmed in Express.
  • CORS headers are missing from error responses. With Nginx add_header without always and with Apache Header set, the header appeared on a 200 response but not on a 404 or 500. The browser then reports a CORS error and hides the real error.
  • The header is added twice. If your application and your reverse proxy both add it, the response contains two Access-Control-Allow-Origin lines, which browsers reject. I reproduced this with Nginx in front of Express.
  • A wildcard is combined with credentials. The value * cannot be used for requests that send cookies. The Express cors package with origin: '*' and credentials: true sends both headers, and browsers refuse that combination.
  • You are calling the wrong URL. A typo returns the default 404 page, which has no CORS headers. If the response body is HTML, read our guide to the DOCTYPE error.
  • PHP sends the header too late. If output has already started, header() fails with Cannot modify header information - headers already sent.
  • A proxy, CDN or firewall drops or replaces the headers on the way.

How to check what your server really sends

Open the Network tab of your browser and look at both the OPTIONS request and the real request, then read the response headers. To test outside the browser, send the same Origin header:

curl -i -H "Origin: http://localhost:5173" https://api.example.com/users

curl -i -X OPTIONS https://api.example.com/users \
  -H "Origin: http://localhost:5173" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: authorization,content-type"

The first command must show Access-Control-Allow-Origin. The second must return a 2xx status with Access-Control-Allow-Methods and Access-Control-Allow-Headers that cover what your request uses.

Fix in Node.js and Express

Install the middleware with npm install cors. To allow every origin, for example for a public read-only API without cookies:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());   // Access-Control-Allow-Origin: *

For an application with a known frontend, use an allowlist and mount it first:

app.use(cors({
  origin: ['http://localhost:5173', 'https://app.example.com'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 600
}));

app.use(authMiddleware);   // after cors, never before it

In my test, an allowed origin received its own value in Access-Control-Allow-Origin together with Vary: Origin. Another origin received a normal 200 response without the header. The preflight returned 204 with the allowed methods, headers and Access-Control-Max-Age: 600. Because CORS was mounted first, even a 500 error response carried the header.

Fix in Python: Flask and Django

Flask

Install Flask-CORS with pip install flask-cors:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app,
     resources={r"/api/*": {"origins": ["http://localhost:5173", "https://app.example.com"]}},
     supports_credentials=True,
     allow_headers=["Content-Type", "Authorization"])

Plain CORS(app) allows every origin. With the configuration above, other origins and routes outside /api/* receive no CORS headers, which I confirmed. The preflight answer lists the allowed headers and methods.

Django

Install django-cors-headers with pip install django-cors-headers and set it up in settings.py:

INSTALLED_APPS = [
    # ...
    "corsheaders",
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",    # as high as possible, before CommonMiddleware
    "django.middleware.common.CommonMiddleware",
    # ...
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",
    "https://app.example.com",
]
CORS_ALLOW_CREDENTIALS = True

Each origin needs its scheme. An entry such as app.example.com fails Django's system check with corsheaders.E013, because it is missing the scheme. By default the preflight answer allows the headers accept, authorization, content-type, user-agent, x-csrftoken and x-requested-with, and a cache time of 86400 seconds.

Fix in Nginx

Nginx needs three details: the always flag, a block for the preflight and a map for several origins.

map $http_origin $cors_origin {
    default "";
    "https://app.example.com" $http_origin;
    "http://localhost:5173"   $http_origin;
}

server {
    # ...
    location /api/ {
        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin $cors_origin always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
            add_header Access-Control-Max-Age 600 always;
            add_header Vary Origin always;
            return 204;
        }

        add_header Access-Control-Allow-Origin $cors_origin always;
        add_header Vary Origin always;
        proxy_pass http://127.0.0.1:3000;
    }
}

Tested results: an allowed origin gets its header on the 200 response and on a 404 from the upstream. Another origin gets no header. The preflight returns 204 with the allowed methods and headers. Three traps are worth knowing:

  • Without always, add_header skips error responses. In my test the header was present on a 200 and missing on a 404 and a 500.
  • Inheritance: if a location block contains any add_header, the add_header lines of the parent server block are no longer applied there. That is why the preflight block repeats them.
  • Duplicates: if the upstream application already sends the header, add proxy_hide_header Access-Control-Allow-Origin; before your own line. Without it, my test response contained the header twice.

Fix in PHP

Send the headers before any output, and answer the preflight:

<?php
$allowed = ['http://localhost:5173', 'https://app.example.com'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

header('Vary: Origin');
if (in_array($origin, $allowed, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

For a public API without cookies, header('Access-Control-Allow-Origin: *'); is enough, as long as the OPTIONS request also returns early with a 2xx status. Put this code at the very top of the file, or in a shared bootstrap file. A blank line or an echo before it triggers the warning Cannot modify header information - headers already sent, and the header is not sent. I reproduced the warning with output buffering turned off.

Fix in Apache

Enable the modules first. On Debian and Ubuntu: sudo a2enmod headers rewrite, then reload Apache. Put these lines in the virtual host or in .htaccess:

SetEnvIf Origin "^(https://app\.example\.com|http://localhost:5173)$" ORIGIN_OK=$0
Header always set Access-Control-Allow-Origin "%{ORIGIN_OK}e" env=ORIGIN_OK
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
Header always merge Vary Origin

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=204,L]

In my test, an allowed origin received its header on a 200 and on a 404, another origin received none, and the OPTIONS request returned 204 with the allowed methods and headers. As with Nginx, always matters: with plain Header set, my 404 response carried no CORS header.

Local development: use a proxy, not a browser extension

During development, the simplest fix is to make the browser believe that frontend and API share an origin. A dev server proxy forwards the requests. In Vite:

// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    }
  }
});

Now call fetch('/api/users') with a relative URL. I tested this with a backend that sends no CORS headers: the request through the Vite server at port 5173 returned the JSON, while a direct request to the API showed no CORS header. Webpack has an equivalent devServer.proxy option, and its syntax depends on the version. If Vite warns about an ES module in a CommonJS file, name the file vite.config.mjs or set "type": "module" in package.json.

These shortcuts are not fixes, and none of them belongs in production:

  • Browser extensions and --disable-web-security change only your own browser. Your users do not have them, and they remove a protection from that browser.
  • mode: 'no-cors' sends the request but gives you an opaque response that your code cannot read.
  • Public CORS proxy services route your data through a third party and are not reliable.

In production, either configure CORS on the API as shown above, or serve the frontend and the API from the same origin behind one reverse proxy.

Inspect the API response once CORS works

When the request finally succeeds, check the payload before you debug your frontend code. Paste the response into the JSON Validator to confirm that it is valid JSON and to read the exact parser error if it is not. For a long response, the JSON Formatter makes the structure readable. If the body turns out to be an HTML page, the problem is the URL or the server, not CORS, and our DOCTYPE guide shows how to find it. Avoid pasting production tokens or private data into any online tool.

FAQs

What is a preflight OPTIONS request, and why does it fail?

Before a non-simple request, the browser sends an OPTIONS request to ask the server for permission. It must return a 2xx status with Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers that cover the real request. It fails when the route or an auth layer rejects OPTIONS with 401, 403, 404 or 405, when the framework does not handle OPTIONS, or when Authorization or Content-Type is missing from the allowed headers. Mount the CORS middleware first. The Access-Control-Max-Age header lets browsers cache the answer.

How do I send cookies or an Authorization header across origins?

On the client, use fetch(url, { credentials: 'include' }). On the server, send Access-Control-Allow-Credentials: true with one specific origin and not *, and list the allowed headers and methods explicitly, because wildcards are not honoured for requests with credentials. In the stacks above, that is credentials: true in Express, supports_credentials=True in Flask-CORS and CORS_ALLOW_CREDENTIALS = True in Django. Cookies sent across sites also need the right SameSite and Secure attributes. Never copy the Origin header into the response without checking it against an allowlist, because that lets any website read data on behalf of your logged-in users.

Why does the request work in Postman but fail in the browser?

Postman and curl do not enforce CORS, and they do not send a preflight request. Only the browser checks the response headers. Send your request with an Origin header, as shown in the check section, and fix whatever header is missing.