一起学习网 一起学习网


简单天气应用程序构建

开发 天气应用, API获取数据, 前端开发, Node.js, JavaScript 02-06

构建一个简单的天气应用程序:从API获取数据并在前端显示

在这篇文章中,我们将创建一个简单的天气应用程序,该应用程序能够从公开的天气API中获取天气数据,并在前端显示给用户。我们将使用HTML、CSS和JavaScript构建前端,并用Node.js设置一个简单的服务器。

功能概述

  1. 用户可以输入城市名称。
  2. 应用程序从天气API获取该城市的天气数据。
  3. 在页面上显示温度、天气描述等基本信息。

步骤1:设置项目结构

首先,我们需要设置基本的项目结构:

weather-app/
    ├── public/
    │   ├── index.html
    │   ├── styles.css
    │   └── script.js
    ├── server.js
    └── package.json

步骤2:创建基本的HTML文件

public/index.html中创建一个基本的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>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Weather App</h1>
    <input type="text" id="city" placeholder="Enter city name">
    <button id="getWeather">Get Weather</button>
    <div id="weatherResult"></div>

    <script src="script.js"></script>
</body>
</html>

步骤3:设计基本的CSS

public/styles.css中添加一些基本样式:

body {
    font-family: Arial, sans-serif;
    text-align: center;
    margin-top: 50px;
}

#weatherResult {
    margin-top: 20px;
    font-size: 1.2em;
}

步骤4:实现前端JavaScript逻辑

public/script.js中添加JavaScript代码以处理用户输入和API请求:

document.getElementById('getWeather').addEventListener('click', function() {
    const city = document.getElementById('city').value;
    if (city) {
        fetch(`/weather?city=${city}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById('weatherResult').innerText = data.error;
                } else {
                    document.getElementById('weatherResult').innerText = 
                        `Temperature in ${city}: ${data.temperature}°C, ${data.description}`;
                }
            })
            .catch(error => console.error('Error fetching weather data:', error));
    } else {
        document.getElementById('weatherResult').innerText = "Please enter a city name.";
    }
});

步骤5:创建Node.js服务器

server.js中,设置一个简单的Express服务器来处理API请求:

const express = require('express');
const fetch = require('node-fetch');
const app = express();

app.use(express.static('public'));

app.get('/weather', async (req, res) => {
    const city = req.query.city;
    const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
    const apiUrl = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;

    try {
        const response = await fetch(apiUrl);
        const data = await response.json();

        if (data.cod !== 200) {
            res.json({error: data.message});
        } else {
            res.json({
                temperature: data.main.temp,
                description: data.weather[0].description
            });
        }
    } catch (error) {
        res.json({error: "Error fetching data from API"});
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

步骤6:启动应用程序

确保你已经安装了expressnode-fetch模块:

npm init -y
npm install express node-fetch

然后在项目目录下运行以下命令启动服务器:

node server.js

现在就可以打开浏览器,访问http://localhost:3000,输入城市名称,查看天气信息了。

结论

此天气应用程序通过前端与后端的简单交互展示了从API获取信息并显示在页面上的基本技术。你可以根据需要进一步扩展功能,例如添加更多天气信息或优化UI。


编辑:一起学习网