-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (58 loc) · 1.8 KB
/
app.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
const dotenv = require("dotenv");
const express = require("express");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const helmet = require("helmet");
const compression = require("compression");
const { AppError, globalErrorHandler } = require("./utils");
const { clientRouter, projectRouter, userRouter } = require("./resources");
// Set environment variables
if (process.env.NODE_ENV !== "production") {
dotenv.config({ path: "process.env" });
}
// Connect to mongo DB
require("./db");
const app = express();
// Secure HTTP headers
app.use(
helmet({
contentSecurityPolicy: {
useDefaults: true,
directives: {
scriptSrc: ["'self'", "'unsafe-inline'"]
}
}
})
);
// Development logging
if (process.env.NODE_ENV !== "production") {
app.use(morgan("dev"));
}
// Compress text data
app.use(compression());
// Body parser
app.use(express.json({ limit: "10kb" }));
// Set CORS headers so that React SPA is able to communicate with this server
app.use(cors());
// Set up routes
app.use("/api/v1/projects", projectRouter);
app.use("/api/v1/clients", clientRouter);
app.use("/api/v1/users", userRouter);
// Heroku deployment --- serve static assets in production
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client", "build")));
app.get("*", (req, res) =>
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
);
}
// Handle 404 (Not Found) errors
app.all("*", (req, res, next) => {
next(new AppError(404, `Cannot find ${req.originalUrl} on this server`));
});
// Handle all errors
app.use(globalErrorHandler);
// Connect to server
const PORT = process.env.PORT || 6000;
// eslint-disable-next-line
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}...`));