使用body-parser处理Express服务端POST请求的天气查询功能实现
基于Node.js Express框架的天气查询服务实现
实现逻辑
- 基于Express搭建本地Web服务
- 通过Express内置的
urlencoded中间件解析POST请求携带的城市名参数 - 调用OpenWeatherMap开放接口获取对应城市的实时天气数据
- 解析接口返回的JSON数据,组装成前端可展示的内容后响应
完整可运行代码
后端服务代码
const express = require('express') const https = require('https') const app = express(); const bodyParser = require('body-parser'); // 解析POST请求的表单参数 app.use(express.urlencoded({extended:false})); // 首页路由返回查询页面 app.get('/',(req,res)=>{ res.sendFile(__dirname + "/index.html") }) // 处理天气查询请求 app.post('/',(req,res)=>{ const query = req.body.cityName; // 建议自行前往OpenWeatherMap官网申请专属密钥替换此处公开密钥 const appkey = "a602ee18b63e10a1276ceb0896049408"; // 拼接接口请求地址,units=metric指定返回摄氏度单位,lang=zh_cn返回中文天气描述 const url = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURI(query)}&appid=${appkey}&units=metric&lang=zh_cn` https.get(url,(response)=>{ // 接口请求失败处理 if(response.statusCode !== 200){ res.send("<h1>查询失败,请检查输入的城市名称是否正确</h1>") return } response.on("data",(data)=>{ const weatherData = JSON.parse(data); const temp = weatherData.main.temp; const weatherDescription = weatherData.weather[0].description; const icon = weatherData.weather[0].icon; const iconUrl = `http://openweathermap.org/img/wn/${icon}@2x.png` // 组装返回内容 res.write(`<p>当前天气:${weatherDescription}</p>`); res.write(`<h1>${query}当前温度为${temp}℃</h1>`); res.write(`<img src="${iconUrl}" alt="天气图标">`); res.send(); }) }) }) // 监听3000端口启动服务 app.listen(3000,()=>{ console.log("server is running on port 3000"); });
前端查询页面代码(index.html)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>天气查询</title> </head> <body> <form action="/" method="POST"> <input type="text" name="cityName" placeholder="请输入城市名,如Beijing、上海" required> <button type="submit">查询天气</button> </form> </body> </html>
运行步骤
- 初始化项目:执行
npm init -y - 安装依赖:执行
npm install express body-parser - 将上述两份代码存放在项目根目录下,后端代码命名为
app.js - 启动服务:执行
node app.js - 浏览器访问
http://localhost:3000即可使用天气查询功能
内容的提问来源于stack exchange,提问作者Pintu_111
相关产品推荐
相关产品推荐

