feat: implement weather fetching API and update frontend components for improved user experience

This commit is contained in:
2025-08-03 19:10:20 +02:00
parent b6b6146ad0
commit 43262846a5
8 changed files with 140 additions and 77 deletions

63
backend/routes/api.js Normal file
View File

@@ -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;

View File

@@ -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 });
});

View File

@@ -1,11 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Backend | <%= title %></title>
</head>
<body>
You have reached the backend views index page.
</body>
</html>
</head>
<body>
<h1>You have reached the backend views index page!</h1>
<p>Currently, there is nothing to display!</p>
</body>
</html>