-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
59 lines (43 loc) · 1.67 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
var express = require("express");
var app = express();
const cors = require('cors')
require('url').URL;
dotenv = require('dotenv').config()
let myKey = process.env.REACT_APP_API_KEY;
let timeKey = process.env.REACT_APP_TIMEZONE_KEY;
const fetch = require("node-fetch");
app.get("/", (req, res) => {
res.sendFile(process.cwd() + "/views/index.html");
})
app.get("/api/geo/:input", (req, res) => {
//required because node-fetch doesn't support Unicode fetch.
let url = new URL('http://api.openweathermap.org/geo/1.0/direct?q=' + sanitize(req.params.input) + '&limit=5&appid=' + myKey)
fetch(url)
.then(response => response.json())
.then(json => res.send(json));
})
app.get("/api/air/:lat/:lon", (req, res) => {
fetch('http://api.openweathermap.org/data/2.5/air_pollution?lat=' + req.params.lat + '&lon=' + req.params.lon + '&appid=' + myKey)
.then(response => response.json())
.then(json => res.send(json));
})
app.get("/api/time/:lat/:lon", (req, res) => {
fetch('http://api.timezonedb.com/v2.1/get-time-zone?key=' + timeKey + '&format=json&by=position&lat=' + req.params.lat + "&lng= +" + req.params.lon)
.then(response => response.json())
.then(response => res.send(response))
.catch(err => console.log("The server time error: " + err));
})
app.use(express.static(__dirname + '/public'));
app.use(cors());
app.get("*", (req, res) => {
res.status(404);
res.redirect("/")
}) //handle erroneous paths
let port = process.env.PORT || 3000;
app.listen(port, () => {
console.log('Listening on port ' + port);
});
function sanitize(input){
let regex = /^([a-zA-Z0-9\u0080-\u024F]+(?:\. |-| |'))*[a-zA-Z0-9\u0080-\u024F]*$/;
return regex.test(input) ? input : "error";
}