-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
43 lines (37 loc) · 1.17 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
const express = require('express')
const app = express()
const request = require('request');
const bodyParser = require('body-parser');
let port = process.env.PORT
if (port == null || port == ""){
port = 3002
}
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json())
app.set('views', 'views')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.render('index')
})
app.post('/', (req, res) => {
const apiKey = '91983b527b411f8743b8a2b0f1654e4f'
let city = req.body.city
let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`
request(url, (err, response, body) => {
if(err){
res.render('index', {weather: null, error: 'Error, please try again'});
} else {
let weather = JSON.parse(body)
if(weather.main == undefined){
res.render('index', {weather: null, error: 'Error, please try again'});
} else {
let weatherText = `It's ${weather.main.temp} degrees in ${weather.name}!`;
res.render('index', {weather: weatherText, error: null});
}
}
})
})
app.listen(port, () => {
console.log("server running " + port)
})