Weather Api incorporation to our website (Express)
// Requiring and bindingExpress
const express=require("express");
const app=express();
//Requiring Body-parser
const bodyParser=require("body-parser");
// Requirng Https
const https= require("https");
//Using Body-parser with express
app.use(bodyParser.urlencoded({extended:true}));
// Get request using Express
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/index.html")
});
app.post("/",(req,res)=>{
console.log();
// Incororating API Endpoint
const appKey = "d482678f9db290646f15671a90add5ee";
const query = req.body.cityName;
const unit="metric";
const url= "https://api.openweathermap.org/data/2.5/weather?q="+query+"&appid="+appKey+"&units="+unit;
// Get request using HTTPS
https.get(url,(response)=>{
// Capturing data from the end point using on method
response.on("data",(data)=>{
const weatherData= JSON.parse(data);
const temp= weatherData.main.temp;
const description=weatherData.weather[0].description;
const icon=weatherData.weather[0].icon;
const imageUrl="http://openweathermap.org/img/wn/" + icon + "@2x.png"
res.write("<p>The Weather is currently: "+description+ "</p>")
res.write("<img src="+imageUrl+">");
res.write("<h1>The temperature in "+query+" is "+ temp +" degrees Celcius</h1>")
res.send();
});
});
})
app.listen(3000,()=>{
console.log("Server up and Running");
});
Comments
Post a Comment