← Back to Error Lab

CORS Error: Access to fetch at 'API' from origin 'APP' has been blocked by CORS policy

Published 2026-05-06

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web pages from making requests to a different domain than the one that served the web page. This error indicates that your frontend application (e.g., running on localhost:3000) is attempting to call an API (e.g., on api.example.com) that hasn't explicitly permitted requests from your frontend's origin. The browser blocks the response from reaching your code to protect users from cross-site request forgery (CSRF) attacks. This is strictly a browser-enforced rule; tools like cURL or Postman will not experience CORS errors because they do not implement this security policy. The fix must almost always be implemented on the server side.

Fix / Solution

Configure the backend server to include the appropriate `Access-Control-Allow-Origin` headers in its responses. During development, you might set this to `*` or `http://localhost:3000`. In production, specify the exact domain of your frontend. If you cannot modify the backend, use a proxy server (like Vite's dev server proxy or a Cloudflare Worker) to forward the request from the same origin.

Code Snippet

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

// ✅ Fixed — Express.js Backend configuration
const express = require('express');
const cors = require('cors');
const app = express();

// Allow requests from specific origin
app.use(cors({
  origin: 'https://lordorange.top'
}));

app.get('/data', (req, res) => {
  res.json({ message: 'Success' });
});