cors in express

  1. Install the cors package using npm:
npm install cors
  1. Import the cors module in your Express application:
const express = require('express');
const cors = require('cors');
const app = express();
  1. Enable CORS for all routes in your Express application:
app.use(cors());
  1. 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));
  1. Alternatively, configure CORS to allow multiple origins:
const corsOptions = {
  origin: ['https://example1.com', 'https://example2.com'],
  optionsSuccessStatus: 200,
};

app.use(cors(corsOptions));
  1. Handle CORS for specific routes:
app.get('/api/data', cors(), (req, res) => {
  // Your route logic here
  res.json({ message: 'Data from API' });
});
  1. Configure CORS for preflight requests (HTTP OPTIONS):
app.options('/api/data', cors());
  1. Handle specific HTTP methods with CORS:
const corsOptions = {
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
};

app.use(cors(corsOptions));
  1. Set allowed headers for CORS:
const corsOptions = {
  allowedHeaders: 'Content-Type,Authorization',
};

app.use(cors(corsOptions));
  1. Set credentials option for cross-origin requests with credentials:
const corsOptions = {
  credentials: true,
};

app.use(cors(corsOptions));
  1. 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));