-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (66 loc) · 2.04 KB
/
server.js
File metadata and controls
77 lines (66 loc) · 2.04 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
71
72
73
74
75
76
77
// Declaring requirements
const express = require("express");
const path = require("path");
const fs = require("fs");
// Creating an instance of express
const app = express();
// Adding a Port assigned by Heroku, or 3000 if avaliable
const PORT = process.env.PORT || 3000;
// Sets up data parsing middleware
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
// Adding a test route
app.get("/api/config", (req, res) => {
res.json("Route created");
});
// Get route for notes
app.get("/notes", (req, res) => {
res.sendFile(path.join(__dirname, "/public/notes.html"));
});
// Get route for reading db.json
app.get("/api/notes", (req, res) => {
fs.readFile("./db/db.json", (err, data) => {
if (err) throw err;
return res.json(JSON.parse(data));
});
});
// Post route for adding to db.json file
app.post("/api/notes", (req, res) => {
fs.readFile("./db/db.json", (err, data) => {
if (err) throw err;
req.body.id = Date.now();
const noteList = JSON.parse(data);
noteList.push(req.body);
console.log(noteList);
fs.writeFile("./db/db.json", JSON.stringify(noteList), (err) => {
if (err) throw err;
console.log("The file has been saved!");
});
res.json(req.body);
});
});
app.delete("/api/notes/:id", (req, res) => {
fs.readFile("./db/db.json", (err, data) => {
if (err) throw err;
const noteList = JSON.parse(data);
const noteId = req.params.id;
const newList = noteList.filter(note => {
return note.id != noteId;
});
console.log(newList);
fs.writeFile("./db/db.json", JSON.stringify(newList), (err) => {
if (err) throw err;
console.log("The file has been deleted!");
});
res.end();
});
});
// Get route for wildcard
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "/public/index.html"));
});
// Listening on assigned Port
app.listen(PORT, () => {
console.log(`App is running on http://localhost:${PORT}`);
});