-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
63 lines (48 loc) · 1.43 KB
/
server.js
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
58
59
60
61
62
63
import express from 'express';
import path from 'path';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import userRoutes from './backend/routes/userRoutes.js';
import { notFound, errorHandler } from './backend/middleware/errorMiddleware.js';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
// MongoDB Connection
const MONGO_URI = process.env.MONGO_URI;
if (!MONGO_URI) {
console.error('MongoDB connection string is missing in environment variables');
process.exit(1);
}
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
}
connectDB();
// Serve static files from the React app
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, 'dist')));
//useRoutes
app.use('/api/users', userRoutes);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
// Your routes here
app.get('/api/test', (req, res) => {
res.send('API is working!');
});
app.use(notFound);
app.use(errorHandler);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});