-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (47 loc) · 1.71 KB
/
index.js
File metadata and controls
62 lines (47 loc) · 1.71 KB
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
import express from "express";
import axios from "axios";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// Set EJS as templating engine
app.set("view engine", "ejs");
app.set('views', path.join(__dirname, "views"));
// Serve static files
app.use(express.static(path.join(__dirname, "public")));
// Body parser middleware
app.use(express.urlencoded({ extended: true }));
// Home route
app.get("/", (req, res) => {
res.render("index", { joke: null, name: "" });
});
// Form submission route
app.post("/get-joke", async (req, res) => {
const name = req.body.name.trim();
if (!name) return res.render("index", { joke: "Please enter your name!", name: '' });
try {
const response = await axios.get("https://v2.jokeapi.dev/joke/Any?type=single,twopart");
const jokeData = response.data;
let joke = "";
if (jokeData.type === "single") {
joke = jokeData.joke;
} else if (jokeData.type === "twopart") {
joke = `${jokeData.setup} ... ${jokeData.delivery}`;
}
// Replace placeholders with user's name
joke = joke
.replace(/Chuck Norris/gi, name)
.replace(/\bHe\b/gi, name)
.replace(/\bHis\b/gi, `${name}'s`)
.replace(/\bHim\b/gi, name);
res.render('index', { joke, name });
} catch (error) {
console.error(error);
res.render('index', { joke: "Could not fetch a joke. Try again later.", name });
}
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});