Web Development Critical API Error

How to Fix CORS Error: No 'Access-Control-Allow-Origin' Header

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.
Quick Fix
# Express: npm install cors && app.use(require('cors')()) # Django: pip install django-cors-headers

Why Does This Happen?

Browsers enforce CORS: when your frontend (e.g. React on port 3000) calls a backend API on a different port or domain, the backend MUST include Access-Control-Allow-Origin in its response headers. If it does not, the browser blocks the response.

Step-by-Step Solution

1
Fix in Node.js / Express
Install and apply the cors middleware:
Terminal / Code
npm install cors

// server.js
const cors = require('cors');
app.use(cors()); // Allow all origins (dev)
// OR restrict to your frontend (production):
app.use(cors({ origin: 'http://localhost:3000' }));
Place app.use(cors()) before your route definitions.
2
Fix in Python Django
Install django-cors-headers and configure settings.py:
Terminal / Code
pip install django-cors-headers

# settings.py
INSTALLED_APPS += ['corsheaders']
MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ...]
CORS_ALLOWED_ORIGINS = ['http://localhost:3000']
CorsMiddleware must be placed before CommonMiddleware.
3
Fix in Python Flask
Use flask-cors:
Terminal / Code
pip install flask-cors
from flask_cors import CORS
CORS(app)
Restrict to specific routes: CORS(app, resources={r'/api/*': {'origins': 'http://localhost:3000'}})
4
Fix in FastAPI
Add CORSMiddleware:
Terminal / Code
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:3000'], allow_methods=['*'], allow_headers=['*'])
Use allow_origins=['*'] during early local development.

Common Mistakes to Avoid

Trying to fix CORS from the frontend JavaScript (adding headers in fetch). CORS headers must come from the backend server.
Using a CORS browser extension as a permanent fix in production.

Frequently Asked Questions

Why does Postman work but the browser gives a CORS error?
CORS is a browser-only security policy. Postman is not a browser and does not enforce it.

Learn to Write Code That Doesn't Break

DoxaTech Hub's 10-month programme teaches you Git internals, Linux systems, C, Python, SQL, Docker, and React from first principles — so you spend less time fixing errors and more time shipping.

Start Learning →