-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
94 lines (79 loc) · 2.32 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
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
93
94
// Dependencies
// =============================================================
var express = require("express");
var bodyParser = require("body-parser");
var path = require("path");
// Sets up the Express App
// =============================================================
var app = express();
var PORT = process.env.PORT || 3000;
// Sets up the Express app to handle data parsing
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Star Wars Characters (DATA)
// =============================================================
var characters = [
{
routeName: "yoda",
name: "Yoda",
role: "Jedi Master",
age: 900,
forcePoints: 2000
},
{
routeName: "darthmaul",
name: "Darth Maul",
role: "Sith Lord",
age: 200,
forcePoints: 1200
},
{
routeName: "obiwankenobi",
name: "Obi Wan Kenobi",
role: "Jedi Master",
age: 55,
forcePoints: 1350
}
];
// Routes
// =============================================================
// Basic route that sends the user first to the AJAX Page
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "view.html"));
});
app.get("/add", function(req, res) {
res.sendFile(path.join(__dirname, "add.html"));
});
// Get all characters
app.get("/all", function(req, res) {
res.json(characters);
});
// Search for Specific Character (or all characters) - provides JSON
app.get("/api/:characters?", function(req, res) {
var chosen = req.params.characters;
if (chosen) {
console.log(chosen);
for (var i = 0; i < characters.length; i++) {
if (chosen === characters[i].routeName) {
return res.json(characters[i]);
}
}
return res.json(false);
}
return res.json(characters);
});
// Create New Characters - takes in JSON input
app.post("/api/new", function(req, res) {
// req.body hosts is equal to the JSON post sent from the user
// This works because of our body-parser middleware
var newcharacter = req.body;
newcharacter.routeName = newcharacter.name.replace(/\s+/g, "").toLowerCase();
console.log(newcharacter);
characters.push(newcharacter);
res.json(newcharacter);
});
// Starts the server to begin listening
// =============================================================
app.listen(PORT, function() {
console.log("App listening on PORT " + PORT);
});