-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
71 lines (56 loc) · 1.57 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const http = require('http');
const cors = require('cors');
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const APIKEY = "60b10dd473063a06b60eee3b342c75a6"; //signup at api.openweathermap.org and obtain an API Key
var options = {
host: 'api.openweathermap.org',
port: 80,
path: '/data/2.5/weather?q=Tokyo,jp&units=metric',
method: 'GET'
};
app.use(cors());
app.set('view engine', 'ejs');
app.get('/', (req,res) => {
res.render('getcity');
});
app.get('/weather',(req,res) => {
var city = req.query.city;
console.log(`City: ${city}`);
setOptionPath(city);
getWeatherDetails().then(data => {
data.city = city.toUpperCase();
res.render('weather', data);
})
});
app.get('/api/weather',(req,res) => {
var city = req.query.city;
console.log(`City: ${city}`);
setOptionPath(city);
getWeatherDetails().then(data => {
res.end.json(data);
})
})
app.listen(process.env.PORT || 8099);
const setOptionPath = (city) => {
options.path = "/data/2.5/weather?q=" + city.replace(/ /g,"+") + "&units=metric&APPID=" + APIKEY;
}
async function getWeatherDetails() {
let currTemp = 'N/A';
let maxTemp = 'N/A';
let minTemp = 'N/A';
let letidity = 'N/A';
const res = await fetch(`http://${options.host}/${options.path}`);
const data = await res.json();
currTemp = data.main.temp;
maxTemp = data.main.temp_max;
minTemp = data.main.temp_min;
humidity = data.main.humidity;
return({
currTemp: currTemp,
maxTemp: maxTemp,
minTemp: minTemp,
humidity: humidity
});
}