You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
404NotFound/server/index.js

85 lines
2.1 KiB

6 months ago
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import session from 'express-session';
import MongoStore from 'connect-mongo';
import authRoutes from './routes/auth.js';
import volunteerRoutes from './routes/volunteer.js';
dotenv.config();
const app = express();
// CORS configuration
app.use(cors({
origin: ['http://localhost:5173', 'http://127.0.0.1:5173'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Accept', 'Authorization'],
}));
app.use(express.json());
// Connect to MongoDB Atlas
mongoose.connect(process.env.MONGODB_URI)
.then(() => {
console.log('Connected to MongoDB Atlas successfully');
})
.catch((err) => {
console.error('MongoDB Atlas connection error:', err);
process.exit(1);
});
// Session configuration with MongoDB Atlas store
app.use(session({
secret: process.env.SESSION_SECRET || 'your-secret-key',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI,
ttl: 24 * 60 * 60, // 1 day
}),
cookie: {
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000, // 1 day
httpOnly: true,
},
}));
// Middleware to attach user to request
app.use(async (req, res, next) => {
if (req.session.userId) {
try {
const user = await mongoose.model('User').findById(req.session.userId);
req.user = user;
} catch (error) {
console.error('Error fetching user:', error);
}
}
next();
});
// Mount routes
app.use('/auth', authRoutes);
app.use('/volunteer', volunteerRoutes);
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
error: 'Something went wrong!',
message: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});