-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (46 loc) · 1.51 KB
/
Copy pathserver.js
File metadata and controls
55 lines (46 loc) · 1.51 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
const path = require("path");
const fs = require("fs");
const express = require("express");
const { json } = require("express");
const app = express();
const PORT = process.env.PORT || 7500;
app.use(express.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.use(express.json());
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/public/index.html"));
});
app.get("/notes", function (req, res) {
res.sendFile(path.join(__dirname, "/public/notes.html"))
});
app.get("/api/notes", function (req, res) {
var apiNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"))
res.json(apiNotes);
});
app.post("/api/notes", function (req, res) {
var body = req.body;
body.id = Math.floor(Math.random() * 1000)
let arrayNote = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
arrayNote.push(body);
fs.writeFileSync("./db/db.json", JSON.stringify(arrayNote), "utf8");
res.json(arrayNote);
});
app.delete("/api/notes/:id", function (req, res) {
const { id } = req.params;
var deleteArray = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
console.log(deleteArray);
console.log(id);
for (i = 0; i < deleteArray.length; i++) {
if (id == deleteArray[i].id) {
deleteArray.splice(i, 1);
fs.writeFileSync("./db/db.json", JSON.stringify(deleteArray), "utf8");
res.json(deleteArray);
break;
}
}
})
app.listen(PORT, function () {
console.log("Listening on PORT: " + PORT)
});