-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (79 loc) · 1.78 KB
/
index.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
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const connection = require("./database/database");
//Models
const Ask = require("./database/scripts/Ask");
const Answer = require("./database/scripts/Answer");
connection
.authenticate()
.then(() => {
console.log("Database connected!");
})
.catch((error) => {
console.log(error);
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/", function (req, res) {
Ask.findAll({
raw: true,
order: [["id", "DESC"]],
}).then((questions) => {
res.render("index", { questions: questions });
});
});
app.get("/ask", (req, res) => {
res.render("ask");
});
app.post("/save-question", (req, res) => {
var title = req.body.title;
var description = req.body.description;
Ask.create({
title: title,
description: description,
}).then(() => {
res.redirect("/");
});
});
app.get("/ask/:id", (req, res) => {
var id = req.params.id;
Ask.findOne({
where: {
id: id,
},
}).then((question) => {
if (question == undefined) {
res.redirect("/");
}
Answer.findAll({
where: {
askId: question.id,
},
order: [["id", "DESC"]],
}).then((replies) => {
if (replies == undefined) {
res.redirect("/");
}
res.render("reply", {
question: question,
replies: replies,
});
});
});
});
app.post("/reply", (req, res) => {
var content = req.body.content;
var askId = req.body.askId;
Answer.create({
content: content,
askId: askId,
}).then(() => {
res.redirect("/ask/" + askId);
});
});
app.listen(8080, () => {
console.log("Server UP!");
});