-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (53 loc) · 1.58 KB
/
index.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
57
58
59
60
61
62
63
64
65
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const path = require("path");
const fetch = require("node-fetch")
// initialising express app
const app = express();
// setting view engine as ejs
app.set("view engine", "ejs");
// parsing the body values
app.use(bodyParser.urlencoded({ extended: true }));
// adding static files
app.use("/", express.static(path.join(__dirname, "/public")));
// initial page
app.get("/", (req, res) => {
res.render("homePage");
});
// post method for result page
app.post("/", (req, res) => {
const query = req.body.cityName;
const unit = "metric";
const url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=${process.env.API_ID}&units=${unit}`;
fetch(url)
.then((res) => res.json())
.then((data) => {
const weatherInfo = data;
const temp = weatherInfo.main.temp;
const city = weatherInfo.name;
const weatherDescription = weatherInfo.weather[0].description;
const icon = weatherInfo.weather[0].icon;
const image = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
res.render("index", {
city: city,
temp: temp,
weatherDescription: weatherDescription,
image: image,
});
})
.catch((error) => {
if (error) {
res.render("citynameError", {query});
}
});
});
// error page
app.use((req, res) => {
res.render("error");
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`server live at port ${port}`);
});