-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
73 lines (62 loc) · 1.9 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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const baseURL = 'http://api.openweathermap.org/data/2.5/weather?zip=';
const apiKey = process.env.API_KEY;
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
const port = 8080;
const server = app.listen(port, () => {
console.log(`running on localhost: ${port}`);
});
// Server Routes
app.get('/', (request, response) => {
response.sendFile('website/index.html');
});
app.get('/lastEntry', (request, response) => {
response.send(projectData);
});
app.post('/addData', (request, response) => {
const data = request.body;
projectData['date'] = data.date;
projectData['temperature'] = data.temperature;
projectData['userResponse'] = data.userResponse;
response.send(projectData);
});
app.get('/weather', (request, response) => {
const url =
baseURL +
request.query.zipcode +
',us&appid=' +
apiKey +
'&units=imperial';
axios
.get(url)
.then((openWeatherResponse) => {
const weatherData = openWeatherResponse.data;
response.send({
temperature: weatherData.main.temp,
});
})
.catch((error) => {
console.log(error);
response.send({
temperature:
'No temperature was found for this location. Try again!',
});
});
});