Building a Simple Weather App with Node.js and Express

Building a Simple Weather App with Node.js and Express

In this tutorial, we'll explore how to create a simple weather application using Node.js and the Express framework. This application allows users to input a city name and receive real-time weather information from the OpenWeatherMap API.

Prerequisites

Before we get started, ensure you have Node.js installed on your machine. You can download it from nodejs.org.

Setting Up the Project

Let's begin by creating the project structure and installing the required npm packages.

mkdir weather-app

cd weather-app

npm init -y

npm install express https body-parser

Now, let's create two files in the project directory: app.js for the server-side logic and index.html for the client-side form.

'app.js'

// include necessary modules
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");

//create an express app
const app = express();

//Use body-parser middleware
app.use(bodyParser.urlencoded({extended: true}));

//Serve the html file on the root path
app.get("/", function (req, res)
{
    res.sendFile(__dirname + "/index.html");

});

//handle post request for weather data
app.post("/", function (req, res) {
    const query = req.body.cityName;
    const apiKey = "your api key";
    const unit = "metric";
    const url = "https://api.openweathermap.org/data/2.5/forecast?appid=" + apiKey + "&q=" + query + "&units=" + unit;
    // Make an HTTPS GET request to the OpenWeatherMap API to retrieve weather data
    // for the specified city.
    https.get(url, function (response) {
        let data = "";
        // Event listener for data chunks received in the response
        response.on("data", function (chunk) {
            data += chunk;
        });
        // Event listener for the end of the response
        response.on("end", function () {
            try {
                // Parse the received JSON data
                const weatherData = JSON.parse(data);
                console.log("Received weather data:", weatherData);
                // Check if valid weather data is present in the response
                if (weatherData.list && Array.isArray(weatherData.list) && weatherData.list.length > 0) {
                    const temp = weatherData.list[0].main.temp;
                    const weatherDescription = weatherData.list[0].weather[0].description;
                    const icon = weatherData.list[0].weather[0].icon;
                    const imageURL = "https://openweathermap.org/img/wn/" + icon + ".png";
                    // Send HTML response with weather details
                    res.write("<p>The weather is currently " + weatherDescription + "</p>");
                    res.write("<h1>The temperature in " + query + " is " + temp + " degree Celsius.</h1>");
                    res.write("<img src='" + imageURL + "'>");
                    res.send();
                } else {
                    // Log and send a response if no valid weather data is found
                    console.log("No valid weather data found.");
                    res.send("Unable to retrieve weather data. Please check the city name.");
                }
            } catch (error) {
                // Handle errors during JSON parsing and send an error response
                console.error("Error parsing JSON:", error);
                res.send("Error fetching weather data");
            }
        });
    });
});

// Start the server on port 3000 (local port)
app.listen(3000, function () {
    console.log("Server is running on port 3000");
});

'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>

Conclusion

Congratulations! You've just built a simple weather application using Node.js and Express. This project provides a foundation for more advanced features, such as user authentication, additional weather details, or integrating with other APIs.