-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (98 loc) · 2.96 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
// HINTS:
// 1. Import express and axios
import express from "express";
import bodyParser from "body-parser";
import axios from "axios";
const app = express();
const port = 3000;
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
const API_URL = "https://v2.jokeapi.dev/joke/Any?";
app.get("/", async (req, res) => {
// TODO 3: Use axios to PUT the data from req.body to the secrets api servers.
try {
const result = await axios.get(API_URL);
console.log(result.data);
const jokePart = result.data.type;
if (jokePart == "single"){
console.log("It's a single part joke!");
res.render("index.ejs", {
joke: result.data.joke,
type: result.data.category,
language : result.data.lang,
jokePart: jokePart
});
} else if (jokePart == "twopart"){
console.log("It's a two parts joke!");
res.render("index.ejs", {
setup: result.data.setup,
delivery: result.data.delivery,
type: result.data.category,
language : result.data.lang,
jokePart: jokePart
});
}
} catch (error) {
console.log("Error occurs");
console.log(error.response.data);
res.status(500);
}
});
app.post("/", async (req, res) => {
try {
console.log("======================================")
console.log("Request body: ", req.body);
const type = req.body.type;
const languages = req.body.languages;
const jokePart = req.body.part;
const result = await axios.get(
`https://v2.jokeapi.dev/joke/${type}?lang=${languages}&type=${jokePart}`
);
console.log(result.data);
if (!result.data.joke && !result.data.delivery){
console.log("No joke found");
res.render("index.ejs", {
joke: result.data.message,
type: type,
language : languages,
jokePart: jokePart
});
}else{
console.log("Joke found!");
if (jokePart == "single"){
console.log("It's a single part joke!");
res.render("index.ejs", {
joke: result.data.joke,
type: result.data.category,
language : result.data.lang,
jokePart: jokePart
});
} else if (jokePart == "twopart"){
console.log("It's a two parts joke!");
res.render("index.ejs", {
setup: result.data.setup,
delivery: result.data.delivery,
type: result.data.category,
language : result.data.lang,
jokePart: jokePart
});
res.render("index.ejs", {
setup: result.data.setup,
delivery: result.data.delivery,
type: result.data.category,
language : result.data.lang,
jokePart: jokePart
});
}
}
} catch (error) {
console.error("Failed to make request:", error.message);
res.render("index.ejs", {
error: error.message,
joke: null,
});
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});