2025-12-11 22:12:18 +05:30

105 lines
3.6 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
// Load environment variables from root .env file
dotenv.config();
// Log environment variables (for debugging)
console.log('Current working directory:', process.cwd());
console.log('Environment variables loaded:', {
PORT: process.env.PORT,
MONGODB_URI: process.env.MONGODB_URI ? 'MongoDB URI is set' : 'MongoDB URI is not set',
JWT_SECRET: process.env.JWT_SECRET ? 'JWT Secret is set' : 'JWT Secret is not set',
UPLOAD_PATH: process.env.UPLOAD_PATH
});
// Create Express app
const app = express();
// CORS configuration
const corsOptions = {
origin: ['http://localhost:3000', 'http://127.0.0.1:3000', 'http://localhost:3001', 'http://localhost:3002'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],
exposedHeaders: ['Content-Range', 'X-Content-Range'],
credentials: true,
maxAge: 86400, // 24 hours
optionsSuccessStatus: 200
};
// Middleware
app.use(cors(corsOptions));
// Add headers middleware for additional CORS support
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static files from uploads directory
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
// Database connection with better error handling
const connectDB = async () => {
try {
if (!process.env.MONGODB_URI) {
throw new Error('MONGODB_URI is not defined in environment variables');
}
console.log('Attempting to connect to MongoDB...');
const conn = await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 30000, // Increase timeout to 30 seconds
socketTimeoutMS: 45000,
});
console.log(`✅ MongoDB Connected Successfully: ${conn.connection.host}`);
console.log(`Database Name: ${conn.connection.name}`);
} catch (error) {
console.error('❌ MongoDB connection error:', error.message);
console.error('Full error:', error);
console.log('\n⚠ Please check:');
console.log('1. MongoDB Atlas IP whitelist (add 0.0.0.0/0 for testing)');
console.log('2. Database credentials are correct');
console.log('3. Network connection is stable\n');
// Don't exit, let the app run but warn about DB issues
}
};
// Connect to database
connectDB();
// Routes
app.use('/api/auth', require('./src/routes/auth'));
app.use('/api/products', require('./src/routes/products'));
app.use('/api/categories', require('./src/routes/categories'));
app.use('/api/cart', require('./src/routes/cart'));
app.use('/api/orders', require('./src/routes/orders'));
app.use('/api/coupons', require('./src/routes/coupons'));
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
error: err.message || 'Server Error'
});
});
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});