From 2f48a4ce074f92ed18060b0c2a19acc72cb5953e Mon Sep 17 00:00:00 2001 From: Niraj Date: Mon, 17 Feb 2025 14:02:25 +0545 Subject: [PATCH] fix: add dynamic CORS middleware to handle cross-origin requests --- tests/test-metadata-api/index.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/test-metadata-api/index.js b/tests/test-metadata-api/index.js index b689ac0f1..62c25b1a6 100644 --- a/tests/test-metadata-api/index.js +++ b/tests/test-metadata-api/index.js @@ -8,6 +8,24 @@ const swaggerJsdoc = require('swagger-jsdoc'); const app = express(); + +const dynamicCors = (req, res, next) => { + const origin = req.headers.origin + + // Allow requests from any origin but with credentials + res.header('Access-Control-Allow-Origin', origin || '*'); + res.header('Access-Control-Allow-Methods', 'GET,PUT,OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); + res.header('Access-Control-Allow-Credentials', 'true'); + + // Handle preflight requests + if (req.method === 'OPTIONS') { + res.sendStatus(200); + } else { + next(); + } +}; + const dataDir = process.env.DATA_DIR || path.join(__dirname, 'json_files'); if (!fs.existsSync(dataDir)) { @@ -31,6 +49,9 @@ const swaggerOptions = { const swaggerSpec = swaggerJsdoc(swaggerOptions); +// cors enable +app.use(dynamicCors); + // Serve Swagger UI app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));