🔧 Error Fixes
· 1 min read

CORS Error: Blocked by CORS Policy — How to Fix It


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

Your browser is blocking a request to a different domain because the server didn’t include the right CORS headers.

Fix 1: Add CORS Headers to Your API

// Express.js
const cors = require('cors');
app.use(cors());  // Allow all origins

// Or restrict to specific origins
app.use(cors({
    origin: ['http://localhost:3000', 'https://myapp.com'],
}));
# Flask
from flask_cors import CORS
CORS(app)

# FastAPI
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(CORSMiddleware, allow_origins=["*"])

Fix 2: Preflight Request Failing

// ❌ OPTIONS request returns 404 or 405
// Your server needs to handle OPTIONS requests

// Express — cors() middleware handles this automatically
// If not using cors(), add manually:
app.options('*', (req, res) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
    res.sendStatus(204);
});

Fix 3: Use a Proxy in Development

// Vite — vite.config.js
export default {
    server: {
        proxy: {
            '/api': 'http://localhost:8080',
        },
    },
};

// Next.js — next.config.js
module.exports = {
    async rewrites() {
        return [{ source: '/api/:path*', destination: 'http://localhost:8080/:path*' }];
    },
};

Fix 4: Credentials Mode

// ❌ Sending cookies but server doesn't allow credentials
fetch('https://api.example.com', { credentials: 'include' });

// ✅ Server must explicitly allow credentials
// AND cannot use wildcard origin
app.use(cors({
    origin: 'http://localhost:3000',  // Not '*'
    credentials: true,
}));

Fix 5: Nginx Reverse Proxy

# Add CORS headers in Nginx
location /api/ {
    proxy_pass http://backend:8080/;

    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "Content-Type, Authorization";

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

Fix 6: Third-Party API Without CORS

// ❌ External API doesn't support CORS
// You can't fix their server

// ✅ Call it from your backend instead
// Frontend → Your API → External API
app.get('/api/proxy', async (req, res) => {
    const data = await fetch('https://external-api.com/data');
    res.json(await data.json());
});