-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
70 lines (58 loc) · 1.59 KB
/
app.js
File metadata and controls
70 lines (58 loc) · 1.59 KB
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
const express = require("express");
const { connect, get } = require("./utils/database");
const postsRouter = require("./routes/posts");
const cors = require("cors");
const app = express();
// cors (since FE and BE ports are different in dev mode)
// fixes other problems too
app.use(cors());
// request logger
app.use((req, res, next) => {
console.log({
url: req.url,
time: new Date().toLocaleTimeString(),
});
next();
});
// set up input middlewares
app.use(express.json());
// static server
// Visit: `/public/check.txt` to check
app.use(
"/public",
express.static("./public", {
extensions: ["html", "htm", "jpg"],
})
);
// react build folder
// app.use(express.static("./frontend/build")); // CRA
app.use(express.static("./frontend/dist")); // Vite
app.get("/", (req, res, next) => {
res.status(200).send("Server is running fine");
});
app.use("/posts", postsRouter);
// Error sink
app.get("/error-check", (req, res, next) => {
throw new Error("error-check");
// res.status(200).send("Server is running fine");
});
app.get("/error-check-async", (req, res, next) => {
fetch("")
.then(() => {})
.catch((err) => next(err));
});
app.use((err, req, res, next) => {
res.status(err.statusCode || 500).send(err || err.message || "500 error");
console.log(res.statusCode, { err });
});
app.use((req, res) => {
res.send("404");
});
connect()
.then(() => {
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Backend server started on port ${PORT}`);
});
})
.catch((error) => console.log("Server start failed!", { error }));