CORS
CORS is the browser rule that decides which websites may call your API from JavaScript.
In this page:
Syntax
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
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
- Using a wildcard origin with credentials
- Forgetting to handle OPTIONS
- 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: