Fetching Weather Data with Node.js and Express: A Beginner’s Guide

Anshumaan Tiwari
Javarevisited
Published in
3 min readJul 23, 2023

Introduction

Weather data plays a vital role in our daily lives, helping us plan our activities and stay prepared for different weather conditions. As a software developer , I’m here to guide you through the process of fetching weather data for a specific location using Node.js and Express. In this article, we will utilize an API to get real-time weather information and display it in a simple web application. So, let’s get started!

Prerequisites

Before we dive into building our weather app, make sure you have the following:

  1. Basic knowledge of web development.
  2. Familiarity with Node.js. If you don’t have it installed, you can download it from the official website.
  3. An IDE or text editor installed on your computer. I recommend using Visual Studio Code.
  4. A stable internet connection.

Step 1: Setting up the Project Let’s begin by creating a new directory for our project. Open your terminal and run the following commands:

mkdir weather-app
cd weather-app
npm init -y

This will create a new Node.js project with default settings. Next, let’s install the required dependencies using the ‘node-fetch’ package to make HTTP requests:

npm install node-fetch --save

Step 2: Building the Weather App In this tutorial, we will use the OpenWeatherMap API to fetch weather data. To access the API, you need an API key. If you don’t have one, sign up on the OpenWeatherMap website to get your API key.

Now, let’s create a new JavaScript file named ‘app.js’ in the project directory. Open ‘app.js’ in your preferred code editor.

const fetch = require("node-fetch");
// Function to fetch weather data
async function getWeatherData(city) {
const apiKey = "YOUR_API_KEY";
const weatherURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${apiKey}`;
try {
const response = await fetch(weatherURL);
const weatherData = await response.json();
return weatherData;
} catch (error) {
console.log("Error fetching weather data:", error);
throw error;
}
}
// Example usage
getWeatherData("Mumbai")
.then((data) => {
console.log(data); // Display the weather data for Mumbai
})
.catch((error) => {
console.error(error);
});

In this code snippet, we’ve defined an asynchronous function ‘getWeatherData’ that takes a city name as input. Replace ‘YOUR_API_KEY’ with the API key you obtained from OpenWeatherMap. The function constructs the API URL with the specified city and fetches the weather data using the ‘node-fetch’ library.

Step 3: Creating the Web Application with Express Now, let’s integrate our weather data fetching function into an Express web application to display the weather for a user-input location.

First, install Express in your project:

npm install express --save

Create a new file named ‘index.html’ in a ‘views’ folder inside your project directory. Add the following HTML code:

<!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>
<h1>Weather App</h1>
<form action="/weather" method="GET">
<label for="city">Enter City:</label>
<input type="text" id="city" name="city" required>
<button type="submit">Get Weather</button>
</form>
<div id="weather-info">
<!-- Weather data will be displayed here -->
</div>
</body>
</html>

Next, update ‘app.js’ to handle the form submission and display weather data:

const express = require("express");

const app = express();
app.set("view engine", "ejs");

app.use(express.static(__dirname + "/public"));

app.get("/", (req, res) => {
res.render("index");
});
app.get("/weather", async (req, res) => {
const city = req.query.city;
try {
const weatherData = await getWeatherData(city);
res.render("index", { weather: weatherData });
} catch (error) {
res.status(500).send("Error fetching weather data.");
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Weather app is running on port ${PORT}`);
});

Conclusion

Congratulations! You’ve successfully created a weather app using Node.js, Express, and the OpenWeatherMap API. Users can now enter a city name, and the app will fetch and display the weather data for that location.

Feel free to enhance the app further by adding more features like user authentication, multiple location support, or additional weather details. Keep exploring and building exciting projects with Node.js and Express! Happy coding!

YO WAI MO

THANK YOU FOR GIVING YOUR PRECIOUS TIME TO READ MY ARTICLE

--

--

Anshumaan Tiwari
Javarevisited

Software Developer having a little passion for technical content writing