Weather App JS Project – Full Code

Weather App project is a simple project for using weather API. This app is build using Express JS for learning beginners exploring APIs.

This app takes city names as input and displays the weather information of that place. Also the current temperature in degree celcius.

Weather App Source Code

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <form action="/" method="post">
        
        <label for="cityInput"> City Name:</label>
        <input id="cityInput" type="text" name="cityName">
        <button type="submit"> Go</button>
    
    </form> 
</body>
</html>

app.js

const express = require("express");
const https = require('https');
const bodyParser = require("body-parser");
const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.get("/", function(req, res){

    res.sendFile(__dirname + "/index.html")
})
app.post("/", function(req, res){

    const query = req.body.cityName;
    const apiKey = "d6b5462917dd2991ef81dbb470eb5564";
    const unit = "metric"
    const url = "https://api.openweathermap.org/data/2.5/weather?q="+query+"&amp;appid="+ apiKey +"&amp;units=" + unit;

    https.get(url, function(response){
        console.log(response.statusCode);

        response.on("data", function(data){
            const weatherData = JSON.parse(data)
            const temp = weatherData.main.temp;
            const description = weatherData.weather[0].description;

            const icon =  weatherData.weather[0].icon;
            const imgURL = "http://openweathermap.org/img/wn/"+ icon +"@2x.png";

            res.write("&lt;p> The Weather is currently "+ description +"&lt;/p>");
            res.write("&lt;h1>The temperature at "+ query +" is "+temp + " degree Celcius &lt;/h1>")
            res.write("&lt;img src="+ imgURL +">");
            res.send();
        })
    })
})

app.listen(3000, function(){
    console.log("Server is running on port 3000");
})

User input page:

Output Page:

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *