add CORS setting

This commit is contained in:
JamesFlare1212
2025-05-09 10:06:04 -04:00
parent 5382659312
commit 99d1ee0a1e
5 changed files with 57 additions and 14 deletions

47
main.js
View File

@@ -1,6 +1,7 @@
// main.js
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors'; // Import the cors middleware
import { fetchActivityData } from './engage-api/get-activity.mjs';
import { structActivityData } from './engage-api/struct-activity.mjs';
import { structStaffData } from './engage-api/struct-staff.mjs';
@@ -11,13 +12,38 @@ dotenv.config();
// --- Configuration ---
const USERNAME = process.env.API_USERNAME;
const PASSWORD = process.env.API_PASSWORD;
const PORT = process.env.PORT || 3000; // Default to port 3000 if not specified
const PORT = process.env.PORT || 3000;
const FIXED_STAFF_ACTIVITY_ID = process.env.FIXED_STAFF_ACTIVITY_ID || '3350';
const allowedOriginsEnv = process.env.ALLOWED_ORIGINS || '*';
let corsOptions;
if (allowedOriginsEnv === '*') {
corsOptions = { origin: '*' };
} else {
// If ALLOWED_ORIGINS is a comma-separated list, split it into an array
const originsArray = allowedOriginsEnv.split(',').map(origin => origin.trim());
corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (originsArray.indexOf(origin) !== -1 || originsArray.includes('*')) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
}
// --- Initialize Express App ---
const app = express();
// Middleware to parse JSON request bodies (useful if you add POST/PUT later)
// Apply CORS middleware globally FIRST
// This will add the 'Access-Control-Allow-Origin' header to all responses
app.use(cors(corsOptions));
// Middleware to parse JSON request bodies
app.use(express.json());
// --- API Endpoints ---
@@ -32,9 +58,8 @@ app.get('/', (req, res) => {
// GET Endpoint: Fetch structured activity data by ID
app.get('/v1/activity/:activityId', async (req, res) => {
let { activityId } = req.params; // Extract activityId from URL parameter
let { activityId } = req.params;
// Validate activityId: should be 1 to 4 digits
if (!/^\d{1,4}$/.test(activityId)) {
return res.status(400).json({
error: 'Invalid Activity ID format. Activity ID must be 1 to 4 digits (e.g., 1, 0001, 9999).'
@@ -51,7 +76,7 @@ app.get('/v1/activity/:activityId', async (req, res) => {
const activityJson = await fetchActivityData(activityId, USERNAME, PASSWORD);
if (activityJson) {
const structuredActivity = await structActivityData(activityJson);
res.json(structuredActivity); // Assuming structActivityData returns a JSON-friendly object
res.json(structuredActivity);
} else {
res.status(404).json({ error: `Could not retrieve details for activity ${activityId}.` });
}
@@ -72,9 +97,7 @@ app.get('/v1/staffs', async (req, res) => {
try {
const activityJson = await fetchActivityData(FIXED_STAFF_ACTIVITY_ID, USERNAME, PASSWORD);
if (activityJson) {
const staffMap = await structStaffData(activityJson); // This returns a Map
// Convert Map to a plain object for JSON serialization
const staffMap = await structStaffData(activityJson);
const staffObject = Object.fromEntries(staffMap);
res.json(staffObject);
} else {
@@ -89,17 +112,17 @@ app.get('/v1/staffs', async (req, res) => {
// --- Start the Server ---
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
console.log(`Allowed CORS origins: ${allowedOriginsEnv === '*' ? 'All (*)' : allowedOriginsEnv}`);
console.log('API Endpoints:');
console.log(` GET /v1/activity/:activityId (ID must be 1-4 digits)`);
console.log(` GET /v1/staffs`);
console.log(` GET /v1/activity/:activityId (ID must be 1-4 digits)`);
console.log(` GET /v1/staffs`);
if (!USERNAME || !PASSWORD) {
console.warn('Warning: API_USERNAME or API_PASSWORD is not set. Please configure them in your .env file or environment variables.');
}
});
// Graceful shutdown (optional but good practice)
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Server shutting down...');
// Perform any cleanup here
process.exit(0);
});