-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
37 lines (32 loc) · 1.08 KB
/
app.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
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const request = require('request')
const app = express()
require('dotenv').config()
app.set('view engine', 'ejs')
app.set('views', 'views')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', (req, res) => {
res.render('index', { data: null, error: null})
})
app.post('/', (req, res) => {
let city = req.body.city
const key = process.env.API_KEY
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${key}`
request(url, (error, response, body) => {
try {
const data = JSON.parse(body)
const image = data.weather[0].icon
const img = `http://openweathermap.org/img/wn/${image}@2x.png`
res.render('index', { data: data, image: img, error: null })
} catch(err) {
res.render('index', { data: null, error: 'Invalid city name'})
}
})
})
const port = process.env.PORT
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
})