diff --git a/backend/routes/api.js b/backend/routes/api.js new file mode 100644 index 0000000..4e61d80 --- /dev/null +++ b/backend/routes/api.js @@ -0,0 +1,63 @@ +import { Router } from "express"; +import dotenv from "dotenv"; + +const router = Router(); +dotenv.config(); + +router.get("/fetchWeather", async (req, res) => { + const city = req.query.city; + const units = req.query.units; + const apiKey = process.env.API_KEY; + + try { + const locationResponse = await fetch( + `https://api.openweathermap.org/geo/1.0/direct?q=${city}&appid=${apiKey}` + ); + if (!locationResponse.ok) { + return res.status(404).json({ + error: "Error fetching location data. (Error: x32)", + success: "false", + data: null, + }); + } + const location = await locationResponse.json(); + if (!location || !location[0]) { + return res.status(404).json({ + error: "Location not found.", + success: "false", + data: null, + }); + } + + const lat = location[0].lat; + const lon = location[0].lon; + + const weatherResponse = await fetch( + `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=${units}` + ); + + if (!weatherResponse.ok) { + return res.status(500).json({ + error: "Unexpected error! (Error: x33)", + success: "false", + data: null, + }); + } + + const weather = await weatherResponse.json(); + + res.status(200).json({ + error: "false", + success: "Weather data fetched successfully!", + data: weather, + }); + } catch (err) { + res.status(500).json({ + error: "Server error", + success: "false", + data: null, + }); + } +}); + +export default router; diff --git a/backend/server.js b/backend/server.js index 1484b05..a50e483 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,7 +1,7 @@ import express from "express"; import cors from "cors"; -import env from "dotenv"; -env.config(); +import apiRouter from "./routes/api.js"; + const app = express(); const port = 7001; @@ -10,6 +10,8 @@ app.use(express.urlencoded({ extended: true })); app.set("view engine", "ejs"); app.use(express.json()); +app.use("/api", apiRouter); + app.get("/", (req, res) => { res.render("index.ejs", { title: port }); }); diff --git a/backend/views/index.ejs b/backend/views/index.ejs index 96ced98..6d616c7 100644 --- a/backend/views/index.ejs +++ b/backend/views/index.ejs @@ -1,11 +1,12 @@ -
- - + + +Currently, there is nothing to display!
+ +