-
Notifications
You must be signed in to change notification settings - Fork 510
Expand file tree
/
Copy pathserver.js
More file actions
57 lines (48 loc) · 1.71 KB
/
Copy pathserver.js
File metadata and controls
57 lines (48 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const thoughtRoutes = require('./routes/thoughtsRoutes');
const app = express();
// 📌 Middleware
app.use(cors()); // Enable CORS for cross-origin requests
app.use(express.json()); // Parse JSON request bodies
// 📌 Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("✅ Connected to MongoDB"))
.catch((err) => {
console.error("❌ MongoDB connection error:", err);
process.exit(1); // Exit the server if the database connection fails
});
// 📌 Default API Route
app.get('/', (req, res) => {
res.json([
{ "path": "/", "methods": ["GET"], "middleware": ["anonymous"] },
{ "path": "/thoughts", "methods": ["GET", "POST"], "middleware": ["anonymous"] },
{ "path": "/thoughts/:id/like", "methods": ["POST"], "middleware": ["anonymous"] }
]);
});
// 📌 Use Thought Routes
app.use('/thoughts', thoughtRoutes);
// 📌 Error Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log error stack for debugging
res.status(500).json({ error: 'An internal server error occurred.' });
});
// 📌 Start the Server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
});
// Handle uncaught exceptions and unhandled rejections
process.on('uncaughtException', (err) => {
console.error("❌ Uncaught Exception:", err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error("❌ Unhandled Rejection at:", promise, "reason:", reason);
process.exit(1);
});