6 min read
ā¢Question 10 of 28mediumWhat is CORS and how does it work?
Understanding Cross-Origin Resource Sharing.
What You'll Learn
- What CORS is
- How it works
- How to configure it
What is CORS?
CORS (Cross-Origin Resource Sharing) is a security mechanism that restricts web pages from making requests to a different domain.
Same-Origin Policy
Browsers block requests to different origins by default:
code.jsJavaScript
Origin = Protocol + Domain + Port
https://example.com:443
ā ā ā
protocol domain portHow CORS Works
Simple Requests
code.jsJavaScript
Browser sends request with Origin header
Server responds with Access-Control-Allow-Origin
Browser allows/blocks based on responsePreflight Requests (OPTIONS)
code.jsJavaScript
For non-simple requests (PUT, DELETE, custom headers):
1. Browser sends OPTIONS request first
2. Server responds with allowed methods/headers
3. If allowed, browser sends actual requestImplementation
code.jsJavaScript
// Express.js
const cors = require('cors');
// Allow all origins
app.use(cors());
// Specific configuration
app.use(cors({
origin: ['https://example.com', 'https://app.example.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
// Manual headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://example.com');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});