From 6a3acc7482dc54c4d013f4c5e2fa8491bb4561de Mon Sep 17 00:00:00 2001 From: Astri4-4 Date: Tue, 12 Aug 2025 11:50:45 +0000 Subject: [PATCH] Fix cors issues --- backend/server.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/backend/server.js b/backend/server.js index 1371162..d4ef7d4 100644 --- a/backend/server.js +++ b/backend/server.js @@ -18,12 +18,36 @@ dotenv.config(); const app = express(); +// CORS Configuration for production deployment +const corsOptions = { + origin: function (origin, callback) { + // Allow requests with no origin (like mobile apps or curl requests) + if (!origin) return callback(null, true); + + // Get allowed origins from environment variable + const allowedOrigins = process.env.CORS_ORIGIN ? + process.env.CORS_ORIGIN.split(',').map(url => url.trim()) : + ['http://localhost:3000', 'https://localhost', 'http://localhost']; + + if (allowedOrigins.indexOf(origin) !== -1) { + callback(null, true); + } else { + console.warn(`CORS blocked origin: ${origin}`); + callback(new Error('Not allowed by CORS')); + } + }, + credentials: true, + methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], + optionsSuccessStatus: 200 // Some legacy browsers choke on 204 +}; + // INITIALIZE DATABASE // Increase body size limits for file uploads app.use(express.urlencoded({extended: true, limit: '500mb'})); app.use(express.json({limit: '500mb'})); -app.use(cors()) +app.use(cors(corsOptions)) // ROUTES app.use("/api/users/", UserRoute);