DocuCenter/backend/server.js

54 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-12-13 17:04:15 -07:00
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const connectDB = require('./src/utils/database');
//Import routes
const userRoutes = require('./src/routes/userRoutes');
const authRoutes = require('./src/routes/authRoutes');
const documentRoutes = require('./src/routes/documentRoutes');
const app = express();
2024-12-18 11:06:57 -07:00
const corsUrl = process.env.FRONTEND_URL;
2024-12-13 17:04:15 -07:00
app.use(express.urlencoded({ extended: true })); // Parses form data
app.use(express.json()); // Parses JSON data
// Configure CORS to allow specific origins
const allowedOrigins = [
'https://docucenter.mpe.ca', // Production frontend
2024-12-18 11:06:57 -07:00
'http://localhost:5173',
corsUrl // Development frontend
2024-12-13 17:04:15 -07:00
];
const corsOptions = {
origin: (origin, callback) => {
// Allow requests with no origin (e.g., mobile apps or curl)
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Specify allowed HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'], // Specify allowed headers
credentials: true, // Enable cookies and credentials sharing
};
app.use(cors(corsOptions));
// Connect to database
connectDB();
// Middleware
app.use(express.json());
// Routes
app.use('/api/user', userRoutes);
app.use('/api/auth', authRoutes);
app.use('/api/document', documentRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});