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:
Frontend: http://localhost:3000
Backend API: http://localhost:5000
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:
Unauthorized access to APIs
Data leaks between different websites
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:
Simple requests (GET, POST without custom headers)
Preflight requests (OPTIONS request before actual request)
Preflight requests happen when:
You use custom headers
You use PUT, DELETE methods
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)
npm install cors
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.
app.use(cors({
origin: 'http://localhost:3000'
}));
Benefits:
Better security
Controlled access
Join the conversation! Your thoughts help the community grow.