-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
88 lines (73 loc) · 2.51 KB
/
app.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
var express = require("express");
var mongoose = require("mongoose");
var app = express();
var port = process.env.PORT || 5000;
const dotenv = require("dotenv");
dotenv.config({ path: "./.env" });
var morgan = require("morgan");
app.use(morgan("dev"));
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/public", express.static(__dirname + "/public"));
app.use(express.static(__dirname + "public/stylesheets/style.css"));
app.use(express.static(__dirname + "public/javascripts/script.js"));
const { validationResult } = require("express-validator");
//"mongodb://localhost/Code-Quiz-Viola"; //'mongodb://127.0.0.1:27017'
mongoose.connect(process.env.MONGO_URI);
mongoose.connection.on("error", (err) => {
console.log("err", err);
});
mongoose.connection.on("connected", () => {
console.log("Mongoose is connected!!!");
});
var resultsSchema = new mongoose.Schema({
// initials: { type: String, default: '' },
initials: { type: String, match: /^[A-Za-z]{2,3}$/ },
});
var scoreSchema = new mongoose.Schema({
finalScore: Number,
});
//Model
var Users1 = mongoose.model("initials", resultsSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/public/index.html");
});
app.post("/initials", async (req, res) => {
const { initials } = req.body;
const user = new Users1({
initials,
});
const errors = validationResult(req);
const message = "No empty fields.";
if (!errors.isEmpty()) {
return res
.status(400)
.send(
"<h4 style = 'font-family: Arial, Helvetica, sans-serif;'>" +
message +
"<a href = 'form.html' class = 'button'><br>Back</a></h4>"
);
} else {
console.error("An error occurred:", errors);
}
await user.save();
console.log(user);
});
var Users = mongoose.model("finalScore", scoreSchema);
app.post("/finalScore", (req, res) => {
var myData = new Users(req.body);
myData
.save()
.then((item) => {
res.send(
'<body style="background-color:rgba(140, 94, 75);font-family:sans-serif;"><div style="text-align:center;color:white;"><h2 style ="padding-top:30px;">Final Score Saved!</h2> ' +
'<a href = "/"><button style="border-radius:15px;background-color:rgba(220, 53, 69);color:white;"><h2>Back to Quiz</h2></button></a></div></body>'
);
console.log(req.body);
})
.catch((err) => {
res.status(400).send("unable to save to database");
});
});
app.listen(port, () => console.log(`Listening port ${port}....`));