-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (64 loc) · 2.52 KB
/
server.js
File metadata and controls
75 lines (64 loc) · 2.52 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const request = require('request');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const apiKey = '4c28dbc85b488e3afce207bef5fc2ac3';
const weather = {
weather: null,
error: null
};
let timestamp;
const requestWeather = (city) => {
return new Promise((resolve, reject) => {
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
request(url, (err, response, body) => {
const weatherResponse = JSON.parse(body);
if (err) {
//Error message in the case of an issue with the entered string
let errMsg = JSON.stringify(err);
weather.error = 'Error, please try again.';
console.log(`${timestamp} - ${city} - error: ${errMsg}`);
resolve();
} else if (!weatherResponse.name || !weatherResponse.main.temp) {
//Error covering an issue exerienced through the API
weather.error = 'Error, please try again.';
console.log(`${timestamp} - ${city} - unexpected api output: ${body}`);
resolve();
} else {
//weather.weather is directly used by Index.ejs. What you see below is by default in
//celcius, so the formula there is to convert it to F. You'll need to edit this in order
//to change what is shown in the Index.ejs file
var tempObj = (weatherResponse.main.temp * 1.8 + 32);
var myJSON = JSON.stringify(tempObj);
var temp = myJSON.slice(0,2);
weather.weather = `Its ${(temp)}°F in ${city}.`;
weather.error = null;
console.log(`${timestamp} - ${city} - ${body}`);
resolve();
}
});
});
};
const clearWeather = () => {
weather.weather = null;
weather.error = null;
};
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', weather);
res.render("images\photo-1455459182396-ae46100617cb.jpg", {images: image})
});
app.post('/', (req, res) => {
const city = req.body.city;
timestamp = Date.now();
console.log(`${timestamp} - ${city} - weather requested`);
requestWeather(city).then(() => {
res.render('index', weather);
clearWeather();
});
});
app.listen(3000, () => {
console.log('listening on port 3000!');
});