4 min read
•Question 32 of 62mediumHow to handle CORS in Node.js?
Understanding and implementing Cross-Origin Resource Sharing.
What You'll Learn
- What CORS is
- How to enable CORS
- Configuration options
What is CORS?
CORS (Cross-Origin Resource Sharing) is a security feature that restricts web pages from making requests to different domains.
Using cors Package
$ terminalBash
npm install corscode.jsJavaScript
const express = require('express');
const cors = require('cors');
const app = express();
// Enable all CORS requests
app.use(cors());
// Or configure options
app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}));Multiple Origins
code.jsJavaScript
const allowedOrigins = [
'https://example.com',
'https://app.example.com'
];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));Manual CORS Headers
code.jsJavaScript
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});