Skip to main content
Network & HTTP · Developer Error Resolution Lab

Fix CORS Error: No 'Access-Control-Allow-Origin' Header is Present on the Requested Resource

Resolve browser cross-origin resource sharing errors by configuring backend HTTP headers and handling preflight OPTIONS requests.

Triggered Error Message:

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

Customize Solution for Your Environment
// Node.js / Express Middleware Solution
import cors from "cors";

const allowedOrigins = ["http://localhost:3000"];

app.use(cors({
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error("CORS blocked by server policy"));
    }
  },
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
  credentials: true
}));

// Or Next.js Route Handler headers:
export async function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      "Access-Control-Allow-Origin": "http://localhost:3000",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type, Authorization",
      "Access-Control-Max-Age": "86400"
    }
  });
}

Root Cause & Mechanism Analysis

Why does this error occur?

The browser blocks client-side JavaScript requests to a different domain, port, or protocol unless the target server explicitly returns the `Access-Control-Allow-Origin` HTTP header responding to the origin and properly answers the preflight HTTP `OPTIONS` request.

Frequently Asked Questions

Can I use wildcard `*` with credentials?
No! Browsers explicitly reject `Access-Control-Allow-Origin: *` when `credentials: include` is sent.
Why does Postman or cURL work but my browser fails?
CORS is a browser security mechanism; curl and Postman are not web browsers and do not enforce CORS.
Browse All 35 Guides