Introduction

A CORS (Cross-Origin Resource Sharing) error is one of the most common issues developers face when working with web APIs, especially in frontend-backend integration. When your frontend application (like React, Angular, or Vue) tries to call an API hosted on a different domain, browser security blocks the request and throws a CORS error.

Understanding how to fix CORS errors is essential for building modern web applications, REST APIs, and microservices. In this article, we will learn, step by step, how to fix CORS issues in simple terms, with practical examples.

What is CORS (Cross-Origin Resource Sharing)?

CORS is a browser security mechanism that restricts web pages from making requests to domains other than the one that served the page.

Example:

Even though both are on localhost, they are considered different origins because of their different ports.

Why CORS Error Happens

CORS error occurs because browsers enforce the Same-Origin Policy.

This policy prevents:

If the server does not allow requests from another origin, the browser blocks it.

Common CORS Error Message

You might see errors like:

"Access to fetch at 'API_URL' from origin 'http://localhost:3000' has been blocked by CORS policy"

This means the server is not allowing your frontend request.

Step 1: Understand the Request Type

There are two types of requests:

Preflight requests happen when:

Understanding this helps in proper configuration.

Step 2: Enable CORS on Backend Server

The correct way to fix CORS is on the server side, not frontend.

Example: Node.js (Express)

Code
npm install cors
Code
const cors = require('cors');
app.use(cors());

This allows all origins (not recommended for production).

Step 3: Configure Specific Origin (Best Practice)

Instead of allowing all origins, allow only your frontend domain.

Code
app.use(cors({
  origin: 'http://localhost:3000'
}));

Benefits:

Step 4: Set CORS Headers Manually

You can also configure headers manually.

Code
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

Step 5: Handle Preflight Requests (OPTIONS)

Browsers send an OPTIONS request before actual request.

Handle it like this:

Code
app.options('*', cors());

Or manually:

Code
if (req.method === 'OPTIONS') {
  res.sendStatus(200);
}

Step 6: Fix CORS in ASP.NET Core Web API

If you are using ASP.NET Core, configure CORS in Program.cs.

Code
builder.Services.AddCors(options => {
  options.AddPolicy("AllowFrontend",
    policy => {
      policy.WithOrigins("http://localhost:3000")
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

app.UseCors("AllowFrontend");

Step 7: Fix CORS in Django

Install package:

Code
pip install django-cors-headers

Add to settings:

Code
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000"
]

Step 8: Check API Gateway or Proxy

Sometimes CORS error happens due to:

Fix by adding headers in proxy config.

Example (Nginx):

Code
add_header 'Access-Control-Allow-Origin' '*';

Step 9: Avoid Common Mistakes

Step 10: Use Proxy in Development (Temporary Fix)

For development, you can use proxy.

Example (React package.json):

Code
"proxy": "http://localhost:5000"

This avoids CORS during development only.

Step 11: Test and Verify

After fixing CORS:

Ensure headers are present:

Real-World Example

Scenario:

Solution:

Result:

Summary

CORS error is a common issue in modern web development when frontend and backend are hosted on different origins. The correct solution is always to configure the backend server to allow requests from trusted origins. By following steps like enabling CORS, handling preflight requests, setting proper headers, and avoiding common mistakes, you can easily fix CORS errors and build secure, scalable web applications.