Created
June 24, 2017 15:45
-
-
Save bmorelli25/1797363f64cf933f796145cc04604022 to your computer and use it in GitHub Desktop.
weather website with node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express'); | |
| const bodyParser = require('body-parser'); | |
| const request = require('request'); | |
| const app = express() | |
| const apiKey = '*****************'; | |
| app.use(express.static('public')); | |
| app.use(bodyParser.urlencoded({ extended: true })); | |
| app.set('view engine', 'ejs') | |
| app.get('/', function (req, res) { | |
| res.render('index', {weather: null, error: null}); | |
| }) | |
| app.post('/', function (req, res) { | |
| let city = req.body.city; | |
| let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apiKey}` | |
| request(url, function (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(3000, function () { | |
| console.log('Example app listening on port 3000!') | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment