const express = require('express'); const cors = require('cors'); // npm install cors const app = express(); const port = 3000; // Define allowed origins const allowedOrigins = [ 'https://yourfrontend.com', 'https://sub.yourfrontend.com', // Add more specific origins as needed // For development, you might temporarily allow localhost, but remove for production // 'http://localhost:8080' ]; // Configure CORS middleware const corsOptions = { origin: function (origin, callback) { // Allow requests with no origin (like mobile apps or curl requests) if (!origin) return callback(null, true); if (allowedOrigins.indexOf(origin) === -1) { const msg = `The CORS policy for this site does not allow access from the specified Origin: ${origin}`; return callback(new Error(msg), false); } return callback(null, true); }, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed HTTP methods allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // Allowed request headers credentials: true, // Allow cookies to be sent optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200 }; // Apply CORS middleware app.use(cors(corsOptions)); // Your API routes app.get('/api/data', (req, res) => { res.json({ message: 'This is secure data!' }); }); app.post('/api/submit', (req, res) => { res.json({ message: 'Data submitted securely!' }); }); // Start the server app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); });