-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (55 loc) · 2.4 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
import express from "express";
import bodyParser from "body-parser";
import axios from "axios";
const app = express();
const PORT = process.env.PORT || 3000;
const API_URL = "https://v2.jokeapi.dev/joke/";
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.render("index.ejs", { content: "", "category": [], "blacklist":[] });
});
app.get("/submit", (req, res)=>{
res.render("index.ejs", {content: "", "category": [], "blacklist":[]});
});
app.post('/submit', async (req, res) => {
console.log(req.body);
const categories = ["Programming", "Dark", "Pun", "Spooky", "Christmas", "Miscellaneous"];
let categoriesReq = "Any";
if (req.body.category && req.body.category.length < 6) {
categoriesReq = categories[req.body.category[0]];
for (let i = 1; i < req.body.category.length; i++) {
categoriesReq = categoriesReq + "," + categories[req.body.category[i]];
}
}
const blacklistFlags = ["nsfw", "religious", "political", "racist", "sexist", "explicit"];
let blacklists = "";
if (req.body.blacklist) {
blacklists = "?blacklistFlags=" + blacklistFlags[req.body.blacklist[0]];
for (let i = 1; i < req.body.blacklist.length; i++) {
blacklists = blacklists + "," + blacklistFlags[req.body.blacklist[i]];
}
}
const url = API_URL + categoriesReq + blacklists;
console.log(url);
try {
const response = await axios.get(url);
console.log(response.data);
res.render("index.ejs", { "content": response.data, "category": [... req.body.category||[]], "blacklist":[... req.body.blacklist||[]]});
} catch (error) {
if (error.response) {
res.render("index.ejs", { error: error.response.data, "content":"", "category": [], "blacklist":[]});
console.log(error.response.status);
console.log(error.response.data);
} else if (error.request) {
res.render("index.ejs", { error: "Apologies, Something went wrong!", "content":"", "category": [], "blacklist":[] });
console.log(error.toJSON());
} else {
res.render("index.ejs", { error: error.message, "content":"", "category": [], "blacklist":[] });
console.log(error.message);
}
}
});
app.listen(PORT, () => {
console.log(`Server is running on port:${PORT}...`);
});