- Install the
cors
package using npm:
npm install cors
- Import the
cors
module in your Express application:
const express = require('express');
const cors = require('cors');
const app = express();
- Enable CORS for all routes in your Express application:
app.use(cors());
- Specify CORS options if needed. For example, to allow requests from a specific origin:
const corsOptions = {
origin: 'https://example.com',
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
- Alternatively, configure CORS to allow multiple origins:
const corsOptions = {
origin: ['https://example1.com', 'https://example2.com'],
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
- Handle CORS for specific routes:
app.get('/api/data', cors(), (req, res) => {
// Your route logic here
res.json({ message: 'Data from API' });
});
- Configure CORS for preflight requests (HTTP OPTIONS):
app.options('/api/data', cors());
- Handle specific HTTP methods with CORS:
const corsOptions = {
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
};
app.use(cors(corsOptions));
- Set allowed headers for CORS:
const corsOptions = {
allowedHeaders: 'Content-Type,Authorization',
};
app.use(cors(corsOptions));
- Set credentials option for cross-origin requests with credentials:
const corsOptions = {
credentials: true,
};
app.use(cors(corsOptions));
- Customize CORS based on the incoming request:
const corsOptionsDelegate = function (req, callback) {
let corsOptions;
if (/ condition /) {
corsOptions = { origin: true }; // Allow all origins
} else {
corsOptions = { origin: false }; // Disallow all origins
}
callback(null, corsOptions);
};
app.use(cors(corsOptionsDelegate));