-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (70 loc) · 2.09 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
http = require('http');
cors = require('cors');
var express = require('express');
var app = express();
var APIKEY = "f4e09c2c71f7fcc5dbf25f2eebac5d6d"; //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('/', function(req,res) {
res.render('getcity');
});
app.get('/weather',function(req,res) {
var city = req.query.city;
console.log("City: " + city);
setOptionPath(city);
getWeatherDetails(function(data){
data.city = city.toUpperCase();
res.render('weather', data);
});
}); // end of app.get()
app.get('/api/weather',function(req,res) {
var city = req.query.city;
console.log("City: " + city);
setOptionPath(city);
getWeatherDetails(function(data) {
res.json(data);
})
})
app.listen(process.env.PORT || 8099);
function setOptionPath(city) {
options.path = "/data/2.5/weather?q=" + city.replace(/ /g,"+") + "&units=metric&APPID=" + APIKEY;
}
function getWeatherDetails(callback) {
var currTemp = 'N/A';
var maxTemp = 'N/A';
var minTemp = 'N/A';
var humidity = 'N/A';
var wreq = http.request(options, function(wres,res) {
wres.setEncoding('utf8');
wres.on('data', function (chunk) {
var jsonObj = JSON.parse(chunk);
if (!jsonObj.hasOwnProperty("main")) {
jsonObj.main = 'N/A';
}
console.log("Current Temp. : " + jsonObj.main.temp);
console.log("Max Temp : " + jsonObj.main.temp_max);
console.log("Min Temp : " + jsonObj.main.temp_min);
console.log("Humidity : " + jsonObj.main.humidity);
currTemp = jsonObj.main.temp;
maxTemp = jsonObj.main.temp_max;
minTemp = jsonObj.main.temp_min;
humidity = jsonObj.main.humidity;
});
wres.on('error',function(e) {
console.log('Problem with request: ' + e.message);
});
wres.on('end',function(chunk) {
callback({currTemp: currTemp,
maxTemp: maxTemp,
minTemp: minTemp,
humidity: humidity});
});
}); //http.request
wreq.end();
}