Files
rezepte-app/server/index.js

59 lines
1.4 KiB
JavaScript

import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import { connectDB, closeDB } from './db.js';
import recipesRoutes from './routes/recipes.js';
import imagesRoutes from './routes/images.js';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Statische Dateien
app.use(express.static(path.join(__dirname, '../public')));
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
// API Routes
app.use('/api/recipes', recipesRoutes);
app.use('/api/images', imagesRoutes);
// Catch-all Route für SPA
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
// Server starten
async function startServer() {
try {
await connectDB();
app.listen(PORT, () => {
console.log(`Server läuft auf Port ${PORT}`);
console.log(`http://localhost:${PORT}`);
});
} catch (error) {
console.error('Fehler beim Starten des Servers:', error);
process.exit(1);
}
}
// Graceful Shutdown
process.on('SIGINT', async () => {
console.log('\nServer wird heruntergefahren...');
await closeDB();
process.exit(0);
});
startServer();