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

CORS

CORS is the browser rule that decides which websites may call your API from JavaScript.

In this page:

  1. CORS
Syntax
javascript
const cors = require('cors');
app.use(cors());
app.use(cors({ origin: 'https://example.com' }));

CORS

Browsers block cross-origin requests unless the server sends Access-Control-Allow-Origin and related headers. Preflight OPTIONS requests check methods and headers first. In Express the cors middleware sets these headers. Allow only origins you trust.

Note: CORS is enforced by browsers, not by servers or tools like curl.

Example: 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
  1. Using a wildcard origin with credentials
  2. Forgetting to handle OPTIONS
  3. Thinking CORS is a security feature for the server
Chapter Summary
  • Browsers enforce CORS
  • Server sends Allow-Origin headers
  • Preflight uses OPTIONS
  • Allow only trusted origins
🔒

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.