-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
79 lines (65 loc) · 2.01 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import express from 'express';
import 'express-async-errors';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import path from 'path';
import cors from 'cors';
import morgan from 'morgan';
import * as dotenv from 'dotenv';
import jobRouter from './routes/jobRouter.js';
import authRouter from './routes/authRouter.js';
import userRouter from './routes/userRouter.js';
import mongoose from 'mongoose';
import errorHandlerMiddleware from './middleware/errorHandlerMiddleware.js';
import { authenticateUser } from './middleware/authMiddleware.js';
import cookieParser from 'cookie-parser';
import cloudinary from 'cloudinary';
dotenv.config();
const app = express();
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev')); // middleware to log requests
}
app.use(
cors({
origin: [process.env.FRONTEND_URL],
credentials: true,
})
);
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const __dirname = dirname(fileURLToPath(import.meta.url));
app.use(express.static(path.resolve(__dirname, './public')));
app.use(cookieParser());
app.use(express.json());
//test route:
app.get('/api/v1/test', (req, res) => {
res.json({ message: 'The api routing is working' });
});
//job route:
app.use('/api/v1/jobs', authenticateUser, jobRouter);
//auth route:
app.use('/api/v1/auth', authRouter);
//user route:
app.use('/api/v1/users', authenticateUser, userRouter);
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, './public', 'index.html'));
});
//not found middleware"
app.use('*', (req, res) => {
res.status(404).json({ message: 'Route not found' });
});
//error handler middleware:
app.use(errorHandlerMiddleware);
const port = process.env.PORT || 5101;
try {
console.log('Connecting to MongoDB...');
await mongoose.connect(process.env.MONGO_URI);
app.listen(port, () => {
console.log('Server is running on port', port);
});
} catch (error) {
process.exit(1);
}