-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
60 lines (52 loc) · 1.74 KB
/
Copy pathapp.js
File metadata and controls
60 lines (52 loc) · 1.74 KB
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
const express = require("express");
const request = require("request");
const bodyParser = require("body-parser");
const config = require("./config");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function (req, res) {
let weatherData = { weather: null };
let message = null;
return res.status(200).render("index", weatherData);
});
app.post("/", (req, res) => {
let city_name = req.body.city;
const API_Key = config.API_KEY;
let url = `http://api.openweathermap.org/data/2.5/weather?q=${city_name}&units=metric&appid=${API_Key}`;
request(url, (error, response, body) => {
const weatherJSON = JSON.parse(body);
console.log(weatherJSON);
if (weatherJSON.cod == "200") {
let weather = {
city: city_name,
temperature: Math.round(weatherJSON.main.temp),
description: weatherJSON.weather[0].description,
windspeed: weatherJSON.wind.speed,
humidity: weatherJSON.main.humidity,
icon: weatherJSON.weather[0].icon,
pressure: weatherJSON.main.pressure,
success: true,
};
let weatherData = { weather: weather };
return res.render("index", weatherData);
} else if (weatherJSON.cod == "401") {
let weather = {
city: city_name,
success: false,
};
let weatherData = { weather: weather };
return res.render("index", weatherData);
} else if (weatherJSON.cod == "404") {
let weather = {
city: city_name,
success: false,
};
let weatherData = { weather: weather };
return res.render("index", weatherData);
}
});
});
app.listen(process.env.PORT || 3000, function () {
console.log("Weather App is listening...");
});