-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
71 lines (59 loc) · 2.48 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
const express = require("express");
const createError = require("http-errors");
const morgan = require("morgan");
require("dotenv").config();
const cors = require("cors");
const enforce = require("express-sslify"); // used to enforces HTTPS connections on any incoming GET and HEAD requests
const path = require("path");
const compression = require("compression");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(morgan("dev"));
// the 3 lines below are commented because we want to return the frontend and not backend upon user request (line 59)
// app.get("/", async (req, res, next) => {
// res.send({ message: "Awesome it works 🐻" });
// });
/**
* So our API call from the client side (port 3000) can be proxy-ed to backend (defined in this app.js file)
* Another way to do this is to define the proxy property in package.json => what we're doing
* */
const corsOptions = {
origin: "http://localhost:3000",
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
// this line has to be above the codes where we serve static files and send frontend codes when user make request in production
app.use("/api", require("./routes/api.route"));
// Serving static files in Express, in Production
if (process.env.NODE_ENV === "production") {
app.use(compression());
app.use(
enforce.HTTPS({
trustProtoHeader: true,
})
);
// if we're in production, we want to be able to serve all static files (which run on browswer side) in our /build folder. `/build` is what gets built when we run the build script in package.json
app.use(express.static(path.join(__dirname, "frontend/build")));
// if client hits any route, backend will send over the index.html in our build (which holds all of our frontend codes!)
app.get("*", function (req, res) {
res.sendFile(path.join(__dirname, "frontend/build", "index.html"));
});
}
// Whenever an app tries to load a service worker, it will be looking for a service-worker.js file
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.resolve(__dirname, "..", "build", "service-worker.js"));
});
app.use((req, res, next) => {
next(createError.NotFound());
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.send({
status: err.status || 500,
message: err.message,
});
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log("Server started on port ", PORT));