-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (41 loc) · 1.41 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
const dotenv = require("dotenv"); // to access environmental variables
const { readFile } = require("fs").promises;
const path = require("path");
// express.js stuff
const express = require("express"); // to set up the RESTful server
const expressLayouts = require("express-ejs-layouts");
// middleware
const cors = require("cors");
// custom routers
const productRouter = require("./routes/products");
dotenv.config(); // reading env variables
const app = express();
// view engine stuff
app.set("view engine", "ejs");
app.set("views", __dirname + "/views");
app.set("layout", "layouts/layout");
// static files
app.use(express.static(__dirname + "/public"));
app.use(cors()); // cross origin resource sharing set up!
app.use(express.json()); // JSON format responses
app.use(expressLayouts); // EJS Layouts
app.use(express.urlencoded({ extended: true })); // allows us to access the form stuff
const PORT = 8000;
async function fetchProducts() {
try {
rawProductData = await readFile(
path.join(__dirname, "products.json"),
"utf8"
);
// productsData is a global variable
global.productsData = JSON.parse(rawProductData);
} catch (error) {
console.error(error);
}
}
app.get("/", async (req, res) => {
res.render("index", { products: productsData });
});
app.use("/product", productRouter);
fetchProducts();
app.listen(process.env.PORT || PORT);