
Updated On : 14-10-2025
CORS Explained — Cross-Origin Resource Sharing को सरल हिंदी में समझें
क्या आप कभी React ऐप से API कॉल करते हुए यह एरर देख चुके हैं — "Access to fetch at '...' from origin '...' has been blocked by CORS policy"
? चिंता न करें — यह ब्राउज़र का सुरक्षा नियम है, न कि आपकी API का बेमतलब का फेलियर। इस लेख में हम CORS (Cross-Origin Resource Sharing) की मूल अवधारणा, preflight कैसे काम करता है, जरूरी HTTP headers और practical fixes — step-by-step, हिंदी में समझाएंगे।
CORS क्या है — सरल परिभाषा
CORS (Cross-Origin Resource Sharing) एक browser-side mechanism है जो यह नियंत्रित करता है कि एक origin (domain + protocol + port) दूसरी origin से resources (API responses, fonts, images) कब और कैसे access कर सकती है। यह सुरक्षा-रक्षा के लिए Same-Origin Policy (SOP) की सीमाओं को नियंत्रित करने का तरीका है।
Same-Origin Policy (SOP) — क्यों जरूरी है
Same-Origin Policy कहता है कि एक webpage केवल उसी origin की resources पढ़ सकता है जिससे वह लोड हुआ है। यह malicious website को किसी और site से sensitive data चुराने से रोकता है। पर कई वैध use-cases होते हैं — जैसे SPA (Single-Page App) जो अलग API domain पर host होता है। ऐसे में CORS उस सुरक्षित रास्ते को तय करता है जिससे browser cross-origin requests की अनुमति दे सकता है।
मुख्य CORS HTTP headers
नीचे कुछ मुख्य headers हैं जो server response में भेजे जाते हैं — इनसे browser तय करता है कि request allow होगी या नहीं:
Access-Control-Allow-Origin
— कौन-सा origin allow है (e.g.,https://example.com
या*
)Access-Control-Allow-Methods
— कौन-से HTTP methods allow हैं (e.g.,GET, POST, PUT, DELETE, OPTIONS
)Access-Control-Allow-Headers
— कौन-से custom headers client भेज सकता है (e.g.,Content-Type, Authorization
)Access-Control-Allow-Credentials
— credentials (cookies, Authorization header) भेजने की अनुमति (value:true
)Access-Control-Expose-Headers
— browser को किन response headers की access देंAccess-Control-Max-Age
— preflight response cache होने का समय (seconds)
Preflight request क्या है — कब और क्यों
जब browser को लगता है कि request “simple” नहीं है (उदाहरण: method POST with Content-Type other than text/plain, application/x-www-form-urlencoded या custom headers), तो browser पहले एक OPTIONS
request भेजता है — इसे preflight कहते हैं। Server को preflight का उत्तर सही Access-Control headers के साथ देना चाहिए वर्ना main request भेजा ही नहीं जाएगा।
Simple request vs Non-simple
- Simple: GET/POST with limited Content-Type (text/plain, form). Usually browser sends directly.
- Non-simple: PUT, DELETE, POST with JSON (
application/json
), custom headers likeAuthorization
— browser does preflight.
Examples — Browser flow और implementation
1) Basic fetch from browser (frontend)
// client (React / plain JS)
fetch('[https://api.example.com/data](https://api.example.com/data)', {
method: 'GET',
headers: { 'Accept': 'application/json' },
// credentials: 'include' // only if sending cookies
})
.then(r => r.json())
.then(data => console.log(data))
.catch(err => console.error(err));
यदि [https://api.example.com](https://api.example.com)
response में Access-Control-Allow-Origin: [https://your-app.com](https://your-app.com)
नहीं भेजेगा, तो browser यह request ब्लॉक कर देगा और console में CORS error दिखेगा।
2) Node.js + Express — सरल CORS setup
// server.js (Express)
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: '[https://your-app.com](https://your-app.com)', credentials: true }));
app.get('/data', (req, res) => {
res.json({ hello: 'world' });
});
app.listen(3000);
यह easiest तरीका है — cors
middleware सभी जरूरी headers add कर देता है।
3) Manual headers (when fine control चाहिए)
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '[https://your-app.com](https://your-app.com)');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
4) React dev setup और proxy
Development में Create React App पर package.json
में "proxy": "http://localhost:3000"
डालकर CORS pain घटाया जा सकता है — पर यह production fix नहीं है।
Common CORS errors और कैसे debug करें
- Blocked by CORS policy — सबसे सामान्य। check server response headers; server पर सही
Access-Control-Allow-Origin
लगा है या नहीं। - Preflight failed (OPTIONS) — server ने OPTIONS request संभाला ही नहीं। Ensure server responds to OPTIONS with required headers and 2xx/204 status.
- Credentials blocked — अगर client
credentials: 'include'
भेजता है, तो server कोAccess-Control-Allow-Credentials: true
और specific origin (not *) भेजना होगा. - Redirection issues — cross-origin redirects may strip CORS headers; ensure final response includes headers or disable redirect.
Security implications और best practices
CORS का उद्देश्य सुरक्षा बढ़ाना है — पर गलत configuration से vulnerabilities आ सकती हैं:
- Avoid wildcard origin (
*
) when credentials are used. - Explicitly whitelist origins instead of allowing everyone।
- Validate and sanitize inputs server-side — CORS सिर्फ browser protection है, server-side authorization अलग रहेगा।
- Limit exposed headers and allowed methods to minimum required.
Advanced topics
Credentials (cookies / Authorization header)
जब client cookies भेजना चाहता है (fetch(..., { credentials: 'include' })
) तो server response में होना चाहिए:
Access-Control-Allow-Origin: https://your-app.com
(NOT*
)Access-Control-Allow-Credentials: true
Using nginx as reverse proxy to avoid CORS
Production में आप API और frontend को एक ही origin पर serve करके CORS का पूरा मुद्दा ही टाल सकते हैं — nginx proxy या same-domain hosting से। Example nginx snippet:
server {
listen 80;
server_name your-app.com;
location /api/ {
proxy_pass [http://backend:3000/](http://backend:3000/);
proxy_set_header Host $host;
}
location / {
root /var/www/front;
try_files $uri /index.html;
}
}
When to use wildcard *
Public APIs जो credentials नहीं लेते और सही से rate-limited हैं, वे *
का उपयोग कर सकती हैं। पर जब authentication/cookies involved हों, तो specific origin चुनें।
Comparative Analysis — CORS बनाम API Gateway या Auth Token
जब हम CORS की बात करते हैं, तो बहुत से developers इसे authentication system समझ लेते हैं — जबकि यह access control mechanism है, जो browser के स्तर पर काम करता है।
Feature | CORS | API Gateway / Token |
---|---|---|
Purpose | Cross-origin request control | User or App authentication |
Who Enforces It? | Browser (client-side) | Server or API layer |
Typical Error | CORS policy blocked | 401 Unauthorized / 403 Forbidden |
Primary Defense | Access-Control-Allow-Origin headers | JWT / OAuth Tokens |
👉 Quick Insight: CORS browser की side से protection देता है, जबकि authentication tokens server की side से। दोनों साथ मिलकर ही complete security layer बनाते हैं।
Safety Measures — Secure CORS Configuration कैसे करें?
- केवल trusted domains को
Access-Control-Allow-Origin
header में allow करें। - Wildcard (*) का इस्तेमाल avoid करें, खासकर जब credentials या cookies भेजे जा रहे हों।
Access-Control-Allow-Methods
में सिर्फ ज़रूरी HTTP methods (GET, POST आदि) ही रखें।- सुनिश्चित करें कि sensitive APIs public exposure से सुरक्षित हैं।
- Regularly security audit करें ताकि accidental misconfiguration पकड़ी जा सके।
Secret Sanitization — जब API Keys या Tokens पास हों
जब आपका browser या frontend किसी server से data fetch करता है, तो कई बार request में API key या token शामिल होते हैं। ऐसे में sanitization और safe storage बहुत ज़रूरी हो जाते हैं।
- API Keys कभी भी client-side code में hardcode न करें।
- Use environment variables या server proxy layers के ज़रिए key forwarding करें।
- यदि कोई CORS error आ रहा है, तो check करें कि कहीं browser key exposure रोक नहीं रहा।
- Backend layer में request logs sanitize करें ताकि sensitive headers accidentally leak न हों।
- Rotate keys periodically और expired keys revoke करें।
🔐 Real-world Analogy: मान लीजिए आप अपने Wi-Fi का password किसी guest को देते हैं — आप चाहते हैं कि वह limited access में रहे, न कि आपके router settings में घुस जाए। यही logic CORS और secret sanitization दोनों पर लागू होता है।
FAQs — अक्सर पूछे जाने वाले प्रश्न
Q1: क्या CORS server-side fix है या client-side?
A: CORS ब्राउज़र-साइड सुरक्षा है, पर fix server-side headers में करना होता है — इसलिए solution server-side ही देना चाहिए।
Q2: क्या Access-Control-Allow-Origin: *
हमेशा उपयोग कर सकता/सकती हूँ?
A: केवल तब जब आपका API public है और credentials नहीं लेता। अगर cookies या Authorization उपयोग हो रहा है, तो *
इस्तेमाल न करें।
Q3: Preflight क्यों बार-बार हो रहा है?
A: Check Access-Control-Max-Age
header — इसे set करके browser preflight caching बढ़ा सकते हैं। पर browser vendor पर निर्भर करता है कि वह कितना cache रखेगा।
Q4: React dev server पर proxy के बाद production में क्या बदलना चाहिए?
A: Development proxy केवल dev convenience है — production में API को proper CORS headers के साथ host करें या दोनों को same origin पर serve करें (proxy / CDN)।
Q5: क्या CORS किसी API के security vulnerabilities को रोकता है?
A: CORS केवल browser-side protection है। Server-side authorization और input validation हमेशा जरूरी हैं। CORS alone security नहीं है।
Quick troubleshooting checklist (summary)
- Console error पढ़ें — is it blocked by CORS or preflight failed?
- Server response headers देखें (Network tab) — presence of
Access-Control-Allow-Origin
? - OPTIONS handler configured है क्या? 204 या 200 return कर रहा है?
- Are you using credentials? If yes, origin must be exact and
Allow-Credentials: true
set. - Consider proxy / same-origin hosting for production.
📌 Further reading
- AI Agents में Memory कैसे Store होती है? — Memory in AI Agents Explained
- OpenAI और n8n से अपना GitHub Code Reviewer बनाएं | GitHub AI Automation Hindi Guide
- Top AWS Services जो System Design में Game-Changer हैं (2026 Guide)
🧑💻 About the Author
Anurag Rai एक टेक ब्लॉगर और नेटवर्किंग विशेषज्ञ हैं जो Accounting, AI, Game, इंटरनेट सुरक्षा और डिजिटल तकनीक पर गहराई से लिखते हैं।
Post a Comment
Blogger FacebookYour Comment Will be Show after Approval , Thanks