π “No ‘Access-Control-Allow-Origin'” β The Most Hated Error
CORS blocks requests from different origins. Fix it on the server, not on the client. Here’s how.
π Server Fixes
// Node.js (Express)
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // Allow all (not for prod)
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
return res.sendStatus(200); // Preflight response
}
next();
});
// .NET Core (Program.cs)
app.UseCors(policy => policy
.WithOrigins("https://myapp.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
// Nginx (reverse proxy)
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,Content-Type';
β For Development Only (Local Proxy)
- Create React App: Add ‘proxy’ field to package.json
- Webpack dev server: proxy configuration
- Vite: server.proxy setting
- Chrome extension: Disable CORS (only dev, dangerous!)
“Spent 3 hours debugging CORS error. Fixed by adding one header on server. Frontend was never the problem. Always CORS is a server issue.”
