You might want to dynamically determine whether to allow a request based on the origin. Here’s an example that allows origins based on a list or pattern:
const allowedOrigins = ['http://example.com', 'http://another-example.com'];
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) { // Handle no origin (e.g., CURL requests)
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET,POST,PUT,DELETE,OPTIONS',
allowedHeaders: 'Content-Type,Authorization',
credentials: true,
};
app.use(cors(corsOptions));
Leave a Reply