forked from osu-cs290-sp21/final-project-crazy-snake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
69 lines (57 loc) · 1.8 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
var path = require("path")
var express = require("express")
var exphbs = require("express-handlebars")
var bodyParser = require("body-parser")
var fs = require("fs")
// Use server to actually take in player scores.
var scoreData = require("./scores.json")
var app = express()
var port = process.env.PORT || 3000
app.engine("handlebars", exphbs({ defaultLayout: "main" }))
app.set("view engine", "handlebars")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static("public"))
app.get("/", function (req, res, next) {
/* sort leaderboards by score */
scoreData.sort(function (a, b) {
return b.score - a.score
})
res.status(200).render("homePage", { displayAll: true, players: scoreData })
})
app.post("/submit", function (req, res) {
var user = {
name: req.body.name,
score: req.body.score,
}
if (user) {
scoreData.push(user)
fs.writeFile(
"./scores.json",
JSON.stringify(scoreData, null, 2),
function (err) {
if (err) {
res.status(500).send(
"Error writing new data. Try again later."
)
} else {
res.status(200).send()
}
}
)
} else {
res.status(400).send(
"Request needs a JSON body with 'username' and 'score'."
)
}
res.redirect("/")
})
app.get("/scores", function (req, res, next) {
res.status(200).render("homePage", { players: scoreData })
})
app.get("*", function (req, res, next) {
res.status(404).render("404Page")
})
app.listen(port, function () {
console.log("== Server is listening on port", port)
})