,我来为你演示如何在 Bun 环境下用 TypeScript 写一个实时天气预报应用,并提供城市选择功能。
首先,确保你已经安装了 Bun。然后创建一个新的项目目录并进入:
bash
Copy Code
mkdir weather-app cd weather-app
解释
初始化项目并安装需要的依赖:
bash
Copy Code
bun init bun add express bun add node-fetch bun add @types/express -d
解释
我们将使用 Express 作为 Web 服务器框架。node-fetch 用于发送 HTTP 请求获取天气数据。
在项目根目录创建一个 app.ts 文件,写入以下代码:
typescript
Copy Code
import express from 'express'; import fetch from 'node-fetch'; const app = express(); const port = process.env.PORT || 3000; app.use(express.static('public')); app.get('/weather/:city', async (req, res) => { const city = req.params.city; const apiKey = 'YOUR_API_KEY'; const url = `http://api.openweathermap.org/data/2.5/weather?q=$${city}&appid=$${apiKey}`; try { const response = await fetch(url); const data = await response.json(); res.json(data); } catch (error) { console.error('Error fetching weather data:', error); res.status(500).json({ error: 'Failed to fetch weather data' }); } }); app.listen(port, () => { console.log(`Server is running at http://localhost:$${port}`); });
解释
记得将 'YOUR_API_KEY' 替换为你自己从 OpenWeatherMap 获取的 API Key。
然后在项目根目录创建一个 public 目录,并在其中创建一个 index.html 文件:
html
Copy Code
<!DOCTYPE html> <html> <head> <title>Weather App</title> </head> <body> <h1>Weather Forecast</h1> <select id="citySelect"> <option value="London">London</option> <option value="New York">New York</option> <option value="Tokyo">Tokyo</option> <!-- 可以添加更多城市选项 --> </select> <button id="getWeatherBtn">Get Weather</button> <div id="weatherInfo"></div> <script> const citySelect = document.getElementById('citySelect'); const getWeatherBtn = document.getElementById('getWeatherBtn'); const weatherInfo = document.getElementById('weatherInfo'); getWeatherBtn.addEventListener('click', async () => { const city = citySelect.value; const response = await fetch(`/weather/$${city}`); const data = await response.json(); if (response.ok) { const temperature = Math.round(data.main.temp - 273.15); // 转换为摄氏度 weatherInfo.innerHTML = ` <h2>$${data.name}</h2> <p>Temperature: $${temperature}°C</p> <p>Weather: ${data.weather[0].main}</p> `; } else { weatherInfo.innerHTML = '<p>Failed to fetch weather data</p>'; } }); </script> </body> </html>
解释
最后,在 package.json 的 scripts 中添加启动命令:
json
Copy Code
"scripts": { "start": "bun app.ts" }
解释
现在可以运行 bun run start 启动应用,然后在浏览器中访问 http://localhost:3000 查看天气预报页面。
选择一个城市,点击 “Get Weather” 按钮,即可获取该城市的实时天气信息。页面将显示城市名称、温度(摄氏度)和天气状况。
以上就是一个简单的 Bun + TypeScript + Express 实现的天气预报应用示例。你可以在此基础上添加更多功能,如更多城市选项、天气图标显示、未来几天的预报等。