-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
113 lines (99 loc) · 2.6 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const express = require("express");
const app = express();
const Pergunta = require("./database/pergunta"); // Apenas por ser importado, ele executa.
const Resposta = require("./database/resposta");
//Tratando a Conexão
const connection = require("./database/database");
connection
.authenticate()
.then(() => {
console.log("Conexão feita com banco de dados !");
})
.catch((msgErro) => {
console.log(msgErro);
});
//Express usar EJS como "Views Engine"//
app.set("view engine", "ejs");
//Sem ele não consigo modificar o CSS
app.use(express.static("public"));
//Body-Parser//
const bodyParser = require("body-parser");
const pergunta = require("./database/pergunta");
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//Rotas//
app.get("/", (req, res) => {
pergunta.findAll({
raw: true,
order: [
["id", "DESC"]
]
}).then((Perguntas) => {
res.render("Principal.ejs", {
perguntas: Perguntas,
});
});
});
app.get("/perguntar", (req, res) => {
res.render("perguntar.ejs", {});
});
app.post("/salvarpergunta", (req, res) => {
var titulo = req.body.titulo;
var descricao = req.body.descricao;
if (titulo.length !== 0) {
if (descricao.length !== 0) {
Pergunta.create({
titulo: titulo,
descricao: descricao,
}).then(() => {
res.redirect("/");
});
}else{
console.log("");
}
}else{
console.log("");
}});
app.get("/perguntar/:id", (req, res) => {
var id = req.params.id;
Pergunta.findOne({
where: {
id: id
}
}).then(pergunta => {
if (pergunta != undefined) { // Pergunta encontrada
Resposta.findAll({
where: {
perguntaid: pergunta.id
},
order: [
['id', 'DESC']
]
}).then(respostas => {
res.render("pergunta", {
pergunta: pergunta,
respostas: respostas
});
});
} else { // Não encontrada
res.redirect("/");
}
});
})
app.post("/responder", (req, res) => {
var corpo = req.body.corpo;
var perguntaid = req.body.pergunta;
Resposta.create({
corpo: corpo,
perguntaid: perguntaid
}).then(() => {
res.redirect("/perguntar/" + perguntaid);
});
});
//App rodando na porta 4000//
app.listen(3000, (req, res) => {
console.log("Aplcação Rodando");
console.log("listening on http://localhost:3000");
});