Coding Peacefully, Until the Error Hits
Have you ever been coding your frontend app using JavaScript or frameworks like React, Vue, or Next, and then tried to fetch data from an API using fetch()
or axios()
… and suddenly this pops up:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...
If this is your first time seeing it, it probably feels like getting smacked by a digital slipper.
Don’t worry, you’re not alone. Every web developer eventually runs into this. But in this article, we’ll break it down:
- What is CORS?
- Why does this error appear?
- How to solve CORS (from both frontend and backend)
- Pro tips so you don’t just “bypass it blindly”
What Is CORS?
CORS stands for Cross-Origin Resource Sharing.
It’s a security mechanism built into browsers that prevents websites from accessing data from other domains unless explicitly allowed.
For example:
- Your frontend runs on
http://localhost:3000
- But you’re trying to fetch data from
https://api.example.com/data
Since that’s a different origin (different domain/protocol/port), the browser blocks the request and throws the CORS error.
Why Does This Policy Exist?
Because without it, any website could steal your data from other logged-in sites like Gmail or Facebook.
So CORS is like a bouncer. It checks IDs and makes sure you're not trying to sneak into data you shouldn't access.
Where Does the CORS Error Come From?
It’s a common misconception: people think this is a JavaScript error. It’s not.
CORS is NOT an error from:
- React
- Vue
- Axios
- Fetch API
It’s a browser-enforced rule — your code is fine, but the browser stops the request because it thinks it’s unsafe.
Example of CORS Error
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
If https://api.example.com
does not allow your domain, the browser will block the request.
Solutions: How to Fix It?
Remember: CORS is solved on the server-side. But let’s look at both quick workarounds and permanent solutions.
A. Temporary Frontend Fixes (for Dev Only)
1. Use a Proxy in Development
In React (Create React App), add a proxy in package.json
:
"proxy": "https://api.example.com"
Then fetch from /data
, and React will proxy it.
2. Use a CORS Extension
Install Chrome extensions like:
- Allow CORS: Access-Control-Allow-Origin
- CORS Unblock
But only use this locally for testing!
3. Run Chrome Without CORS (not recommended)
Launching Chrome with --disable-web-security
disables CORS. But this removes all browser protection — so don’t use it regularly.
B. Real Solution: Fix CORS on the Server
1. Add Access-Control-Allow-Origin Header
Access-Control-Allow-Origin: *
This allows all origins — good for testing, risky for production.
Example in Node.js (Express):
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/data', (req, res) => {
res.json({ message: 'Hello from server!' });
});
app.listen(4000);
2. Allow Only Specific Origins
app.use(cors({
origin: 'http://localhost:3000'
}));
Or use a whitelist:
const whitelist = ['http://localhost:3000', 'https://myapp.com'];
app.use(cors({
origin: function (origin, callback) {
if (!origin || whitelist.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
3. Add More CORS Headers
For requests with JSON or auth headers:
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
app.use(cors({
origin: '*',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
What Is a Preflight Request?
Sometimes, the browser sends an OPTIONS request before your real API call. This is called a preflight.
If the server doesn’t respond properly to OPTIONS, your request fails. So always allow OPTIONS methods too.
Don’t Just Use Wildcard *
It’s tempting to do this in dev:
app.use(cors({ origin: '*' }));
But in production, avoid wildcards if your API uses authentication or has sensitive data. Use exact domain whitelists instead.
CORS Isn’t the Enemy — It’s Protection
CORS isn’t here to annoy you. It’s there to keep the web safe. It blocks shady websites from hijacking data from other origins.
But yeah, it can be a pain while developing. The good news? Once you understand how it works, it’s easy to fix.
- Frontend alone can’t fix CORS
- The real solution lives on the server
- Stay calm — and never yell at your browser
No comments:
Post a Comment