-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
81 lines (65 loc) · 1.87 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
80
81
import 'express-async-errors';
import express from 'express';
import dotenv from 'dotenv';
import morgan from 'morgan';
import colors from 'colors';
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import helmet from 'helmet';
import xss from 'xss-clean';
import mongoSanitize from 'express-mongo-sanitize';
// DB and authenticateUser
import connectDB from './db/connect.js';
// routers
import authRouter from './routes/authRoutes.js';
import jobsRouter from './routes/jobsRoutes.js';
// Middleware
import notFoundMiddleware from './middleware/not-found.js';
import errorHandlerMiddleware from './middleware/error-handler.js';
import authenticateUser from './middleware/auth.js';
const app = express();
const port = process.env.PORT || 5000;
dotenv.config();
if (process.env.NODE_ENV !== 'production') {
app.use(morgan('dev'));
}
const __dirname = dirname(fileURLToPath(import.meta.url));
// Static assets
app.use(express.static(path.resolve(__dirname, './client/build')));
// Make json data available in controllers
app.use(express.json());
app.use(
helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
'img-src': ["'self'", 'https: data:'],
},
})
);
app.use(xss());
app.use(mongoSanitize());
// Routes
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/api/v1', (req, res) => {
res.send({ msg: 'API' });
});
app.use('/api/v1/auth', authRouter);
app.use('/api/v1/jobs', authenticateUser, jobsRouter);
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, './client/build', 'index.html'));
});
app.use(notFoundMiddleware);
app.use(errorHandlerMiddleware);
const start = async () => {
try {
await connectDB(process.env.MONGO_URL);
app.listen(port, () => {
console.log(`Server is listening on port ${port}`.yellow.bold);
});
} catch (error) {
console.log(error);
}
};
start();