Cálculo 100% en el Navegador • Cero Registros en Servidor • Ejecución Inmediata
Curious TechieCaja de Herramientas
CORS & CSP Security6 min✓ Solución Verificada en Producción • ES

Cómo Solucionar el Error CORS: Falta el Encabezado Access-Control-Allow-Origin

Diagnóstico Paso a Paso y Configuración de Servidores para Errores de Origen Cruzado

Primary Question • Diagnostic Problem

Cómo Solucionar el Error CORS: Falta el Encabezado Access-Control-Allow-Origin

A client-side web application running on Origin A (e.g., https://app.example.com) makes an asynchronous HTTP fetch() or XMLHttpRequest to an API on Origin B (e.g., https://api.example.com). The browser halts the response and logs a fatal CORS security exception.

Console / Terminal Error OutputExact Message
Access to fetch at "https://api.example.com/data" from origin "https://app.example.com" has been blocked by CORS policy: No "Access-Control-Allow-Origin" header is present on the requested resource.
Affected Protocols & Technologies:HTTP/1.1HTTP/2Fetch APIXHR
Secondary Question • Root Cause Mechanics

Why does Cómo Solucionar el Error CORS: Falta el Encabezado Access-Control-Allow-Origin occur?

Primary Root Cause

La Same-Origin Policy (SOP) del navegador bloquea por defecto la lectura de respuestas procedentes de dominios distintos. Sin el encabezado Access-Control-Allow-Origin explícito emitido por el backend, el navegador rechaza la solicitud en JavaScript.

When Origin A calls Origin B, the browser automatically attaches an Origin: https://app.example.com request header. The server must evaluate this header and respond with Access-Control-Allow-Origin. If this header is missing, empty, or mismatches the origin, the browser immediately discards the response payload and raises a JavaScript TypeError.

4. Observable Symptoms

How to Confirm You Are Facing This Exact Issue

1

Red console error: "No Access-Control-Allow-Origin header is present on the requested resource".

2

The JavaScript fetch() promise rejects with a generic TypeError: Failed to fetch.

3

The Network tab shows the HTTP status code (e.g. 200 OK or 500 Internal Server Error), but the Response Preview is completely blank.

4

The API call works perfectly in Postman, curl, or Insomnia, but fails exclusively inside Chrome, Firefox, or Safari.

5. Diagnostic Decision Tree (GEO Engine Logic)

Explicit Diagnostic Reasoning

Follow these diagnostic rules to isolate the root cause within 60 seconds:

Condition:

"If the request succeeds in Postman or curl but fails in your browser"

Probable Cause:

Your backend is functioning properly, but lacks CORS headers (Postman ignores the Same-Origin Policy; browsers enforce it).

Remedial Action:

→ Add CORS middleware to your backend API server.

Condition:

"If the error occurs on an unhandled backend error (e.g. status 500 or 404)"

Probable Cause:

Your global error-handling middleware is returning an error response BEFORE your CORS middleware has a chance to attach headers.

Remedial Action:

→ Ensure CORS middleware is registered at the very top of your backend middleware pipeline.

Condition:

"If the request method is POST, PUT, or DELETE and shows status 405 or 404 on an OPTIONS call"

Probable Cause:

The browser sent a CORS Preflight check that your server failed to handle.

Remedial Action:

→ Enable HTTP OPTIONS preflight handling on your route handlers.

Verification CommandRun in terminal
curl -I -H "Origin: https://app.example.com" https://api.example.com/data

Sends a simulated cross-origin request. Check the response headers for Access-Control-Allow-Origin. If absent, the server configuration is broken.

6. Architectural Strategy

Long-Term Engineering Solution

Configura el servidor para incluir Access-Control-Allow-Origin con el dominio exacto de tu cliente o gestiona las solicitudes preflight OPTIONS devolviendo el código 204.

Architectural Pattern

Inspect the incoming Origin request header, validate it against an allowlist of approved frontend domains, and dynamically reflect that specific origin in the Access-Control-Allow-Origin header, along with Vary: Origin.

Secondary Question • Implementation Pipeline

How do you fix this step-by-step?

1

Identify Approved Frontend Origins

Define the exact scheme, domain, and port of your frontend applications (e.g., https://app.example.com and http://localhost:5173 for local dev).

2

Install or Configure Backend CORS Middleware

In Node.js/Express, install the official cors package and configure origin matching. In Nginx, add header directives.

javascriptCopy Code
import express from 'express';
import cors from 'cors';

const app = express();

const allowedOrigins = [
  'https://app.example.com',
  'http://localhost:5173',
];

// MUST be declared before any route handlers
app.use(cors({
  origin: (origin, callback) => {
    // Allow requests with no origin (like mobile apps or curl)
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Blocked by CORS policy'));
    }
  },
  credentials: true, // Allow cookies / Authorization headers
}));
3

Ensure Error Handlers Attach CORS Headers

When your API throws an unhandled exception (HTTP 500), your error handler must not strip headers. In Express, ensure cors() runs before error routers.

4

Verify with Browser DevTools

Open the Network tab, trigger the fetch call, click the request, and verify that Access-Control-Allow-Origin: https://app.example.com appears under Response Headers.

Common Misconceptions & Pitfalls

What are common misconceptions and mistakes when fixing this?

×

Trying to fix the error in frontend JavaScript by adding mode: "no-cors"

Por qué falla: no-cors turns the response into an "opaque" response with status 0, preventing JavaScript from reading any response data.

✓ Alternativa correcta: Fix the issue on the backend server by configuring Access-Control-Allow-Origin.

×

Using wildcard Access-Control-Allow-Origin: * with credentials: "include"

Por qué falla: Browsers strictly forbid wildcard origins when credentials (cookies or Authorization headers) are present, throwing another CORS error.

✓ Alternativa correcta: Dynamically return the specific requesting origin instead of "*".

×

Adding CORS headers to the client-side fetch request headers

Por qué falla: Access-Control-Allow-Origin is a RESPONSE header sent by servers, not a request header sent by clients.

✓ Alternativa correcta: Configure response headers on your API server.

Threat Analysis & Security Hardening

Can this fix introduce security vulnerabilities?

Misconfiguring CORS can allow malicious third-party websites to make authenticated requests to your API and exfiltrate sensitive user data.

Security Risks If Ignored

  • •Reflecting arbitrary origins without validation allows malicious domains to read private user records.
  • •Combining wildcard origins with internal intranet endpoints exposes internal infrastructure.

Hardening Best Practices

  • ✓Always validate the Origin header against a strict server-side allowlist.
  • ✓Always include the Vary: Origin response header to prevent CDN caches from serving Origin A headers to Origin B.
10. Concrete Code Example

Fixing Missing CORS Headers in Nginx Reverse Proxy

× Broken / Vulnerable Code (nginx)
# BROKEN: Nginx forwards request but omits CORS headers
location /api/ {
    proxy_pass http://backend_upstream;
}
Problema: If the backend fails or omits headers, the browser blocks the frontend from reading the API response.
✓ Fixed / Hardened Code (nginx)
# FIXED: Nginx dynamically checks Origin and sets response headers
location /api/ {
    if ($http_origin ~* "^https?://(app\.example\.com|localhost:5173)$") {
        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
        add_header 'Access-Control-Allow-Credentials' 'true' 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 'Vary' 'Origin' always;
    }

    if ($request_method = 'OPTIONS') {
        return 204;
    }

    proxy_pass http://backend_upstream;
}
Remediación: Validates trusted origins with a regex, adds headers using the always parameter (so headers are present even on 4xx/5xx errors), and handles OPTIONS preflights with 204 No Content.
Direct Technical Answers • Knowledge Base

Frequently Asked Questions About Cómo Solucionar el Error CORS: Falta el Encabezado Access-Control-Allow-Origin

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

Postman is a development tool that does not enforce the browser Same-Origin Policy.

The Same-Origin Policy exists strictly to protect human users navigating the web in browsers. Postman, curl, and backend servers do not run untrusted third-party code in tabs, so they ignore CORS completely.

Did my server actually process the request if a CORS error was thrown?↓

Yes! For simple GET and POST requests, your server executed the code and returned the data.

The browser received the 200 OK response, saw that Access-Control-Allow-Origin was missing, and intercepted the data before your JavaScript could inspect it.