-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
92 lines (80 loc) · 2.61 KB
/
server.js
File metadata and controls
92 lines (80 loc) · 2.61 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Dependencies
const express = require("express");
const fs = require("fs");
const path = require("path");
// Tells node that we are creating an "express" server
const app = express ();
// Initial PORT
const PORT = process.env.PORT || 8080;
let notesData = [];
// Express app to handle data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// Note variables
// GET api/notes route
app.get("/api/notes", function(req, res) {
try {
notesData = fs.readFileSync("db/db.json", "utf8");
notesData = JSON.parse(notesData);
}
catch (err) {
console.log(err);
}
res.json(notesData);
});
// POST api/notes route
app.post("/api/notes", function(req, res) {
try {
notesData = fs.readFileSync("db/db.json", "utf8");
notesData = JSON.parse(notesData);
req.body.id = notesData.length;
notesData.push(req.body);
notesData = JSON.stringify(notesData);
// Writes the new note to file
fs.writeFile("db/db.json", notesData, "utf8", function(err) {
if (err) throw err;
});
res.json(JSON.parse(notesData));
}
catch (err) {
throw err;
console.log(err);
}
});
// Delete the note with selected id
app.delete("/api/notes/:id", function(req, res) {
try {
notesData = fs.readFileSync("db/db.json", "utf8");
notesData = JSON.parse(notesData);
notesData = notesData.filter(function(note) {
return note.id != req.params.id
});
notesData = JSON.stringify(notesData);
fs.writeFile("db/db.json", notesData, "utf8", function(err) {
if(err) throw err;
});
res.send(JSON.stringify(notesData));
// Handling error
}
catch (err) {
throw err;
console.log(err);
}
});
// Routes
// notes.html route when /notes is typed
app.get("/notes", function(req, res) {
res.sendFile(path.join(__dirname, "./public/notes.html"));
});
// index.html when all others have been accessed
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "./public/index.html"));
});
app.get("/api/notes", function(req, res) {
return res.sendFile(path.json(__dirname, "db/db.json"));
});
// LISTENER
app.listen(PORT, function() {
console.log("App listening on PORT: " + PORT);
});