-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (49 loc) · 1.64 KB
/
index.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
require("dotenv").config();
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const products = require("./routes/products.js");
const users = require("./routes/users");
const orders = require("./routes/orders");
const ClientError = require("./models/ClientError.js");
const path = require("path");
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => console.log("Connected to GunnersGear DB..."))
.catch((err) => console.error(err.message));
app.use(express.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
next();
});
app.use(express.static("public"));
app.use("/api/products", products);
app.use("/api/users", users);
app.use("/api/user/orders", orders);
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "frontend/build")));
console.log(path.join(__dirname, "frontend/build"));
}
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "/frontend/build/index.html"));
});
app.use((req, res, next) => {
const error = new ClientError("Could not find this route", 404);
next(error);
});
app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500).json({
error: error.message || "An unknown error occurred",
});
});
let port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));