Skip to content

Instantly share code, notes, and snippets.

@bmorelli25
Created June 24, 2017 15:45
Show Gist options
  • Save bmorelli25/1797363f64cf933f796145cc04604022 to your computer and use it in GitHub Desktop.
Save bmorelli25/1797363f64cf933f796145cc04604022 to your computer and use it in GitHub Desktop.
weather website with node
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