-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (51 loc) · 2.03 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
import express from "express"
import bodyParser from "body-parser"
import axios from "axios"
const app = express()
const port = 3000
const data = ""
app.set("view engine", "ejs")
app.use(express.static("public"))
app.use(bodyParser.urlencoded({ extended: true }))
// Step 1: Make sure that when a user visits the home page,
// it shows a random activity.You will need to check the format of the
// JSON data from response.data and edit the index.ejs file accordingly.
app.get("/", async (req, res) => {
try {
const response = await axios.get(`https://bored-api.appbrewery.com/random/`)
const result = response.data
res.render("index", { data: result })
} catch (error) {
console.error("Failed to make request:", error.message)
res.render("index.ejs", {
error: error.message,
})
}
})
app.post("/", async (req, res) => {
const type = req.body.type
const participants = req.body.participants
try {
const response = await axios.get(`https://bored-api.appbrewery.com/filter?type=${type}&participants=${participants}`)
const result = response.data
const index = Math.floor(Math.random() * result.length)
const selectedResult = result[index]
res.render("index", { data: selectedResult })
} catch (error) {
console.error("Failed to make request:", error.message)
res.render("index.ejs", {
error: error.message,
})
}
// Step 2: Play around with the drop downs and see what gets logged.
// Use axios to make an API request to the /filter endpoint. Making
// sure you're passing both the type and participants queries.
// Render the index.ejs file with a single *random* activity that comes back
// from the API request.
// Step 3: If you get a 404 error (resource not found) from the API request.
// Pass an error to the index.ejs to tell the user:
// "No activities that match your criteria."
})
app.listen(port, () => {
console.log(`Server running on port: ${port}`)
})