← Back to Node.js Course | Chapter 8: Working with APIs | Lesson 4 of 7

CORS क्या है

CORS वह browser rule है जो decide करता है कौन-सी websites JavaScript से आपका API call कर सकती हैं।

In this page:

  1. CORS
Syntax
javascript
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

javascript
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. #}
आम गलतियां
  1. credentials के साथ एक wildcard origin इस्तेमाल करना
  2. OPTIONS handle करना भूल जाना
  3. यह सोचना कि 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.