forked from HackYourFuture/Node.js
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapp.js
More file actions
43 lines (34 loc) · 875 Bytes
/
app.js
File metadata and controls
43 lines (34 loc) · 875 Bytes
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
import express from "express";
import keys from "./sources/keys.js";
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send("Hello, from backend to frontend!");
});
app.post("/weather", async (req, res) => {
const { cityName } = req.body;
if (!cityName) {
return res.status(400).json({
weatherText: "City name is required!",
});
}
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${keys.API_KEY}&units=metric`,
);
const data = await response.json();
if (data.cod === "404") {
return res.status(404).json({
weatherText: "City is not found!",
});
}
res.json({
weatherText: `The temperature in ${data.name} is ${data.main.temp}°C.`,
});
} catch (error) {
res.status(500).json({
weatherText: "Error fetching weather data.",
});
}
});
export default app;