
Updated On : 05-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 चुनें।
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.
5) Example — React App calling GitHub API
मान लीजिए आप एक React app बना रहे हैं और GitHub API (https://api.github.com/users
) से data fetch कर रहे हैं। अगर API में Access-Control-Allow-Origin
header नहीं है, तो आपको यह error मिलेगा:
Access to fetch at 'https://api.github.com/users' from origin 'http://localhost:3000'
has been blocked by CORS policy...
Solution: Server पर proper headers enable करें या proxy का उपयोग करें।
Case Study — Startup Launching React + Node APIs
एक स्टार्टअप ने React frontend (hosted on Netlify) और Node backend (Heroku) deploy किया। उन्हें production में अचानक
“Blocked by CORS policy” error मिला। Fix था: Node server में Access-Control-Allow-Origin
को Netlify domain पर सेट करना और credentials=true जोड़ना।
एक bootcamp छात्र हर बार API call पर CORS error पाकर परेशान था। जब उसे preflight और headers का फर्क समझ आया, तो उसका React + Express project पहली बार बिना error चला।
Browser Support
आज (2025) लगभग 98% modern browsers CORS को support करते हैं (Source: CanIUse). केवल कुछ पुराने mobile browsers में issues मिलते हैं।
📌 Further reading
- The Best Tool for Localization with AI – Lingo
- Top AWS Services Explained — System Design (हिंदी में)
- Tool Calling बनाम MCP — Model Context Protocol सरल में समझें
🧑💻 About the Author
Anurag Rai एक टेक ब्लॉगर और नेटवर्किंग विशेषज्ञ हैं जो Accounting, AI, Game, इंटरनेट सुरक्षा और डिजिटल तकनीक पर गहराई से लिखते हैं।
Post a Comment
Blogger FacebookYour Comment Will be Show after Approval , Thanks