Files
ToDo-App_Node.js_Test/server.js
2025-04-06 15:27:27 +02:00

68 lines
2.3 KiB
JavaScript

// server.js
// Main application file for the Node.js Express server
require('dotenv').config(); // Load environment variables first
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
// Import route handlers
const authRoutes = require('./routes/authRoutes');
const todoRoutes = require('./routes/todoRoutes');
const viewRoutes = require('./routes/viewRoutes');
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3000;
// --- Middleware ---
// Parse JSON request bodies
app.use(express.json());
// Parse URL-encoded request bodies
app.use(express.urlencoded({ extended: true }));
// Parse cookies (needed for JWT authentication)
app.use(cookieParser());
// Serve static files (HTML, CSS, JS) from the 'public' directory
// Files in 'public' will be accessible directly, e.g., /style.css, /script.js
app.use(express.static(path.join(__dirname, 'public')));
// --- Routes ---
// API routes
app.use('/api/auth', authRoutes); // Authentication routes (login, register, logout, status)
app.use('/api/todos', todoRoutes); // Todo CRUD routes (protected by auth middleware inside the router)
// View routes (serving HTML pages)
// These should generally be last, especially the '/' route,
// to avoid conflicts with static files or API routes.
app.use('/', viewRoutes);
// --- Global Error Handler (Basic Example) ---
// Catches errors passed via next(error) or uncaught errors in route handlers
// ***** GEÄNDERT: Sendet jetzt JSON zurück *****
app.use((err, req, res, next) => {
console.error("Global Error Handler:", err.stack || err); // Log the full error stack
// Check if the response headers have already been sent
if (res.headersSent) {
return next(err); // Delegate to default Express error handler if headers are sent
}
// Send a generic JSON error response
res.status(500).json({
message: 'Ein unerwarteter Serverfehler ist aufgetreten.',
// Optional: Nur im Entwicklungsmodus detailliertere Fehler senden
// error: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});
// --- Start Server ---
app.listen(PORT, () => {
console.log(`Server läuft auf http://localhost:${PORT}`);
// Database connection message is handled in db.js
});