CORS is a browser security feature that restricts cross-origin HTTP requests initiated from scripts running in the browser.
CORS allows a web server to tell the browser: “Yes, it's okay for this site (origin) to access my resources.”
Let’s say:
- Your frontend runs on:
http://localhost:3000 - Your backend/API runs on:
http://localhost:5000
This is considered a cross-origin request. Browsers block such requests by default for security reasons.
CORS is a way to say: “Allow it safely.”
When the frontend (JavaScript in the browser) tries to access a resource on a different origin, the browser sends a CORS request.
Sent automatically if:
- Method is
GET,POST, orHEAD - No custom headers
- Content-Type is
application/x-www-form-urlencoded,multipart/form-data, ortext/plain
-
Browser sends the actual request
-
Server responds with CORS headers like:
Access-Control-Allow-Origin: http://localhost:3000 -
If valid → browser lets the JS access the response.
Sent before the actual request to ask permission for:
- Methods like
PUT,DELETE,PATCH - Custom headers
- Other content-types
-
Browser sends an OPTIONS request (preflight)
-
Server responds with:
Access-Control-Allow-Origin: http://localhost:3000 Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: Content-Type, Authorization
-
If valid → browser sends the actual request next.
const express = require('express');
const cors = require('cors');
const app = express();
// Allow all origins (not recommended for production)
app.use(cors());
// Or allow specific origin
// app.use(cors({ origin: 'http://localhost:3000' }));
app.get('/data', (req, res) => {
res.json({ message: 'CORS allowed' });
});
app.listen(5000, () => console.log('Server running on port 5000'));- CORS Policy Blocked: Means the frontend tried to access an endpoint without permission.
- Missing Access-Control-Allow-Origin: The backend didn’t allow the origin.
- Preflight request failed: Usually due to missing method/header permission on the server.
| Term | Meaning |
|---|---|
| CORS | Cross-Origin Resource Sharing |
| Origin | Protocol + Host + Port (e.g., http://localhost:3000) |
| Preflight Request | An OPTIONS request sent before the actual one |
| Access-Control-Allow-Origin | Server header to allow specific frontend origin |
| Browser's Role | Blocks unauthorized cross-origin requests by default |
A React app (localhost:3000) makes an API call to a Node server (localhost:5000). To make this work:
-
The server must include:
Access-Control-Allow-Origin: http://localhost:3000 -
Or configure CORS properly using middleware (like
corspackage in Express)