forked from PacktPublishing/JavaScript-by-Example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
59 lines (52 loc) · 1.49 KB
/
Copy pathapp.js
File metadata and controls
59 lines (52 loc) · 1.49 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
require('dotenv').config();
const express = require('express'),
bodyParser = require('body-parser'),
DarkSky = require('dark-sky'),
forecast = new DarkSky(process.env.DARK_SKY_KEY),
NodeGeocoder = require('node-geocoder');
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.set('port', 3000);
app.get('/getWeather/:latlong', (req, res, next) => {
const latlong = req.params.latlong.split(',');
if(latlong.length === 2) {
const options = {
provider: 'google',
httpAdapter: 'https',
apiKey: process.env.GMAP_KEY,
formatter: null
};
const geocoder = NodeGeocoder(options);
let city;
geocoder
.reverse({lat:latlong[0], lon:latlong[1]})
.then(function(response) {
city = response[0].city;
})
.catch(function(err) {
res.status(500).json({});
next();
});
forecast
.latitude(latlong[0])
.longitude(latlong[1])
.exclude('minutely,hourly,daily,alerts,flags')
.get()
.then(response => {
response.city = city;
res.status(200).json(response);
})
.catch(err => {
res.status(500).json({});
});
}
});
const http = require('http').Server(app);
http.listen(app.get('port'), () => {
console.log(`Express Server Listening on port ${app.get('port')}.`);
});