CORS क्या है
CORS वह browser rule है जो decide करता है कौन-सी websites JavaScript से आपका API call कर सकती हैं।
In this page:
Syntax
const cors = require('cors');
app.use(cors());
app.use(cors({ origin: 'https://example.com' }));
CORS
Browsers cross-origin requests block करते हैं जब तक server Access-Control-Allow-Origin और related headers न भेजे। Preflight OPTIONS requests पहले methods और headers check करती हैं। Express में cors middleware ये headers set करता है। सिर्फ उन origins allow करें जिन पर आप trust करते हैं।
Note:
CORS browsers से enforce होता है, servers या curl जैसे tools से नहीं।
उदाहरण: CORS
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "https://app.example.com");
res.setHeader("Access-Control-Allow-Methods", "GET,POST");
if (req.method === "OPTIONS") { res.statusCode = 204; return res.end(); }
res.end("data");
});
server.listen(0, async () => {
const r = await fetch("http://localhost:" + server.address().port, { method: "OPTIONS" });
console.log(r.status, r.headers.get("access-control-allow-origin"));
server.close();
});
// Output:
// 204 https://app.example.com
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- credentials के साथ एक wildcard origin इस्तेमाल करना
- OPTIONS handle करना भूल जाना
- यह सोचना कि CORS server के लिए एक security feature है
चैप्टर सारांश
- Browsers CORS enforce करते हैं
- Server Allow-Origin headers भेजता है
- Preflight OPTIONS इस्तेमाल करता है
- सिर्फ trusted origins allow करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: