-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
82 lines (68 loc) · 2.31 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
/* eslint-disable */
var express = require('express');
var axios = require('axios');
var _ = require('lodash');
var bodyParser = require('body-parser');
var config = require('./config');
var app = express();
var server = require('http').createServer(app);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Bypassing CORS issue
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.static(__dirname));
app.use(express.static(__dirname + '/style'));
app.get('/', function(req, res) {
res.sendFile('index.html');
})
//This is a test endpoint. Can delete.
app.get('/api', function(req, res) {
res.json("Hello");
});
//This endpoint fetches data from the Dark Sky API.
app.get('/api/forecast', function(req, res) {
var lat = req.query.latitude;
var long = req.query.longitude;
var requestUrl = config.rootUrl + '/' + config.API_KEY + '/' + lat + ',' + long;
axios.get(requestUrl)
.then(function(data) {
res.status(200).json(data.data);
})
.catch(function(error) {
console.log(error);
})
});
//This endpoint is used to get the city, country based on the lat, long.
app.get('/api/location', function(req, res) {
var lat = req.query.latitude;
var long = req.query.longitude;
var requestUrl = config.geocodeUrl + 'latlng=' + lat + ',' + long;
axios.get(requestUrl)
.then(function(data) {
var results = data.data.results[0].address_components;
var city = '';
var country = '';
results.forEach(function(item) {
//check if the types property exists
if (item['types']) {
//extract the state and country values
if (_.isEqual(item['types'], ['locality', 'political'])) {
city = item['long_name'];
}
if (_.isEqual(item['types'], [ 'country', 'political'])) {
country = item['long_name'];
}
}
});
res.status(200).json({ city: city, country: country });
})
.catch(function(error) {
console.log(error);
});
});
server.listen(process.env.PORT || config.port);
console.log('Server running');