🌐 CORS = Cross-Origin Security
Browsers block cross-origin requests. CORS enables secure cross-origin communication. Essential for APIs and frontend apps.
📝 CORS Headers
# Server Headers Access-Control-Allow-Origin: https://myapp.com Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Credentials: true Access-Control-Max-Age: 3600 # Preflight Request OPTIONS /api/data Origin: https://myapp.com Access-Control-Request-Method: POST Access-Control-Request-Headers: Content-Type # Simple Request GET /api/data Origin: https://myapp.com
🎯 CORS Solutions
# 1. Enable CORS on Server (Node.js/Express)
const cors = require('cors');
app.use(cors({
origin: 'https://myapp.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}));
# 2. Enable CORS on Server (.NET Core)
app.UseCors(policy =>
policy.WithOrigins("https://myapp.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
# 3. Enable CORS on Server (Python/Flask)
from flask_cors import CORS
CORS(app, origins=['https://myapp.com'])
# 4. Proxy (Development)
# package.json
{
"proxy": "http://localhost:5000"
}
# 5. Configure CORS in Reverse Proxy (nginx)
location /api {
add_header 'Access-Control-Allow-Origin' 'https://myapp.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
}
# 6. CORS with Credentials (Frontend)
fetch('https://api.example.com/data', {
credentials: 'include'
});
💡 CORS Best Practices
- Don’t use ‘*’ in production
- Use specific origins only
- Use credentials flag carefully
- Cache preflight responses
- Use environment-specific origins
“CORS enables secure cross-origin requests. Essential for modern web APIs.”
