-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
56 lines (47 loc) · 1.49 KB
/
server.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
const express = require("express");
const dotenv = require("dotenv");
const { default: axios } = require("axios");
const pkg = require("../package.json");
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
const apiKey = process.env.OPEN_WEATHER_API;
const baseUrl = "https://api.openweathermap.org/data/2.5";
app.set("json spaces", 2);
app.get("/", (req, res) => {
res.redirect(pkg.homepage);
});
app.get("/api/weather/:city", async (req, res) => {
const { city } = req.params;
axios
.get(`${baseUrl}/weather?q=${city}&appid=${apiKey}`)
.then((response) => {
res.send(response.data);
})
.catch((error) => {
if (error.response) {
res.status(error.response.status).send(error.response.data);
return;
}
res.status(500).send("Server Error");
});
});
app.get("/api/forecast/:city", async (req, res) => {
const { city } = req.params;
axios
.get(`${baseUrl}/forecast?q=${city}&appid=${apiKey}`)
.then((response) => {
res.send(response.data);
})
.catch((error) => {
if (error.response) {
res.status(error.response.status).send(error.response.data);
return;
}
res.status(500).send("Server Error");
});
});
app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Api start running on port ${port}`);
});