CORS Errors - Complete Troubleshooting Guide

Common CORS Error Messages:
• Access to fetch at 'http://localhost:8080/api' from origin 'http://localhost:3000' has been blocked by CORS policy
• Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
• Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response
• Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
💡 What is CORS? Cross-Origin Resource Sharing (CORS) is a security feature that blocks web pages from making requests to a different domain, port, or protocol than the one serving the web page.

Quick Solutions

Development Environment Quick Fix

For development only, you can disable CORS checks:

# Chrome (use for development only!) chrome --user-data-dir="/tmp/chrome_dev" --disable-web-security --disable-features=VizDisplayCompositor # Or use a CORS proxy https://cors-anywhere.herokuapp.com/your-api-url
⚠️ Warning: Never disable CORS in production or use CORS proxies for production applications!

Backend Solutions by Framework

Node.js / Express

Method 1: Using cors middleware

const cors = require('cors'); const app = express(); // Allow all origins (development only) app.use(cors()); // Or configure specific origins app.use(cors({ origin: ['http://localhost:3000', 'http://localhost:4200'], credentials: true }));

Method 2: Manual headers

app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); res.header('Access-Control-Allow-Credentials', true); if (req.method === 'OPTIONS') { res.sendStatus(200); } else { next(); } });
Spring Boot (Java)

Method 1: @CrossOrigin annotation

@RestController @CrossOrigin(origins = "http://localhost:3000") public class ApiController { @GetMapping("/api/data") public ResponseEntity<Data> getData() { // your code } }

Method 2: Global configuration

@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:3000", "http://localhost:4200") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true); } }
Django (Python)

Using django-cors-headers

# Install: pip install django-cors-headers # settings.py INSTALLED_APPS = [ 'corsheaders', # ... other apps ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # ... other middleware ] # Allow specific origins CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://localhost:4200", ] # Or allow all origins (development only) CORS_ALLOW_ALL_ORIGINS = True
Flask (Python)

Using Flask-CORS

# Install: pip install flask-cors from flask import Flask from flask_cors import CORS app = Flask(__name__) # Allow all origins CORS(app) # Or configure specific origins CORS(app, origins=['http://localhost:3000', 'http://localhost:4200']) # Or configure per route from flask_cors import cross_origin @app.route('/api/data') @cross_origin(origins=['http://localhost:3000']) def get_data(): return {'data': 'example'}
ASP.NET Core (C#)

Configure CORS in Startup.cs

public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => { builder.WithOrigins("http://localhost:3000", "http://localhost:4200") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCors("AllowSpecificOrigin"); // ... other middleware }

Frontend Proxy Solutions

React Development

Add proxy to package.json

{ "name": "my-app", "version": "0.1.0", "proxy": "http://localhost:8080", // ... rest of package.json }

Or use custom proxy configuration

// Create setupProxy.js in src folder const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:8080', changeOrigin: true, }) ); };
Angular Development

Create proxy.conf.json

{ "/api/*": { "target": "http://localhost:8080", "secure": true, "changeOrigin": true, "logLevel": "debug" } }

Start with proxy

ng serve --proxy-config proxy.conf.json
Vue.js Development

Configure in vue.config.js

module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }

Common CORS Scenarios

Scenario 1: Simple GET Request

Frontend on localhost:3000 calling API on localhost:8080

Solution:

Scenario 2: POST Request with Custom Headers

Sending POST with Content-Type: application/json

Solution:

Scenario 3: Requests with Credentials

Sending cookies or authorization headers

Solution:

⚠️ Security Best Practices

💡 Debugging Tips

Related Issues