diff --git a/services/requests.js b/services/requests.js index a9c7f4d..d27db0a 100644 --- a/services/requests.js +++ b/services/requests.js @@ -28,10 +28,23 @@ const getAllActivities = (req, res) => { } const getSingleActivity = (req, res) => { - fetch('https://www.boredapi.com/api/activity') // fetch activity from bored API - https://www.boredapi.com/about - .then(data => data.json()) // return a promise containing the response - .then(json => res.json(json)) // extract the JSON body content from the response (specifically the activity value) and sends it to the client - .catch((err) => console.log(err)) // log errors to the console + fetch('https://www.boredapi.com/api/activity') + .then(data => { + if (!data.ok) { + throw new Error(`HTTP error! status: ${data.status}`); + } + const contentType = data.headers.get("content-type"); + if (contentType && contentType.includes("application/json")) { + return data.json(); + } else { + throw new Error("Received non-JSON response"); + } + }) + .then(json => res.json(json)) + .catch((err) => { + console.error("Error fetching activity:", err); + res.status(500).json({ error: "Failed to fetch activity" }); + }); } const addActivityToDB = (req, res) => {