基于中央气象台API的Node.js天气查询服务,支持IP地址自动定位和城市天气查询,提供智能缓存、完整的API文档和测试支持。
git clone <repository-url>
cd weather
npm install
# 开发模式
npm run dev
# 生产模式
npm start
# 启动缓存脚本
npm run cache
# 健康检查
curl http://localhost:3000/health
# 获取省份列表
curl http://localhost:3000/api/provinces
# 获取北京天气
curl http://localhost:3000/api/weather/北京
# 查看API文档
curl http://localhost:3000/api-docs
项目使用Swagger自动生成API文档,访问以下地址查看完整的API文档:
http://localhost:3000/api-docs
GET /health
GET /weatherInfo
GET /api/weather
GET /api/weather/:city
GET /api/weather/code/:cityCode
GET /api/provinces
GET /api/cities/:provinceCode
GET /api/cache/stats
DELETE /api/cache/clear
POST /api/cache/all-cities
# 运行所有测试
npm test
# 运行测试并查看覆盖率
npm run test:coverage
# 运行测试并监听文件变化
npm run test:watch
cityMatcher.test.js:城市匹配器测试weatherCache.test.js:天气缓存测试通过 config.json 文件配置系统行为:
{
"cache": {
"enabled": true,
"ttl": 43200000, // 缓存过期时间(毫秒)
"checkPeriod": 600000, // 缓存检查周期(毫秒)
"autoRefresh": true, // 是否自动刷新缓存
"refreshInterval": 1800000, // 自动刷新间隔(毫秒)
"maxCacheSize": 1000, // 最大缓存大小
"disableWarming": false // 是否禁用缓存预热
},
"weatherApi": {
"baseUrl": "http://www.nmc.cn/f/rest",
"timeout": 10000, // API请求超时时间(毫秒)
"retryAttempts": 3 // API请求重试次数
},
"logging": {
"level": "info",
"enableConsole": true,
"enableFile": true,
"file": "logs/app.log"
},
"server": {
"port": 3000, // 服务器端口
"corsEnabled": true
}
}
./cache_data.json./logs/YYYY-MM-DD.logweather/ ├── app.js # 主应用文件 ├── WeatherCache.js # 天气缓存管理 ├── cityMatcher.js # 城市匹配器 ├── logger.js # 日志系统 ├── cacheWeather.js # 缓存脚本 ├── config.json # 配置文件 ├── china_cities.json # 中国城市数据 ├── cache_data.json # 缓存持久化文件 ├── package.json # 项目配置 ├── .env.example # 环境变量示例 ├── README.md # 项目文档 ├── cityMatcher.test.js # 城市匹配器测试 ├── weatherCache.test.js # 天气缓存测试 ├── test-api.js # API测试脚本 └── logs/ # 日志文件夹
{
"success": true,
"data": {
"location": {
"ip": "0.0.0.0",
"country": "中国",
"province": "北京市",
"city": "北京",
"isp": "中国电信"
},
"weather": {
"city": "北京",
"code": "ABJ",
"temperature": "25",
"humidity": "60",
"pressure": "1013",
"wind": "东北风3级",
"weather": "晴",
"updated_at": "2025-10-01T12:00:00Z",
"source": "中央气象台"
}
},
"meta": {
"response_time": 100,
"timestamp": "2025-10-01T12:00:00Z"
}
}
{
"success": false,
"message": "查询天气信息失败",
"error": "未找到城市: 未知城市",
"meta": {
"response_time": 50,
"timestamp": "2025-10-01T12:00:00Z"
}
}
http://ip.api.xyc.ink/ 获取用户IP对应城市http://www.nmc.cn/f/rest/province 获取省份列表http://www.nmc.cn/f/rest/province/{省份代码} 获取城市列表http://www.nmc.cn/f/rest/real/{城市代码} 获取实时天气npm run dev 启动开发模式,支持热重载npm run test:coverage 查看测试覆盖率MIT License