You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

天气预报项目中Type Error: cannot read property 'cityName' of undefined错误排查

解决TypeError: Cannot read property 'cityName' of undefined的问题

嘿,我一眼就看出问题所在啦——Express默认不会自动解析POST请求的表单数据,这就导致req.body是undefined,你自然没法读取req.body.cityName,所以才会抛出这个类型错误。

下面是具体的修复步骤,分两种情况:

情况1:你的Express版本是4.16.0及以上(推荐)

从Express 4.16.0开始,官方已经把body-parser的核心功能集成到框架里了,不用额外安装包,只需要在代码里加一行中间件配置就行:

const express= require("express"); 
const https = require("https"); 
const app = express(); 

// 关键:添加这行代码,解析表单提交的urlencoded格式数据
app.use(express.urlencoded({ extended: true }));

app.get("/", function(req, res){ 
  res.sendFile(__dirname + "/index.html"); 
}); 

// 你的POST路由代码保持不变就行

情况2:你的Express版本低于4.16.0

如果你的Express版本比较老,那需要先安装body-parser依赖包:

npm install body-parser

然后在代码里引入并使用这个中间件:

const express= require("express"); 
const https = require("https"); 
const bodyParser = require("body-parser"); // 引入body-parser
const app = express(); 

// 配置中间件解析表单数据
app.use(bodyParser.urlencoded({ extended: true }));

// 其余代码保持不变

额外建议:添加错误处理让应用更健壮

修复完核心问题后,建议你给代码加一点错误处理逻辑,比如用户没输入城市名称、API请求失败的情况,避免出现新的报错:

app.post("/", function(req, res){ 
  const query = req.body.cityName;
  
  // 处理用户未输入城市的情况
  if (!query) {
    return res.send("<h1>请输入城市名称再提交哦!</h1>");
  }

  const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0"; 
  const unit ="metric"; 
  const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit; 

  https.get(url, function(response){ 
    console.log(response.statusCode); 

    // 处理API请求失败的情况(比如城市名称错误)
    if (response.statusCode !== 200) {
      return res.send("<h1>找不到这个城市的天气数据,请检查城市名称是否正确!</h1>");
    }

    response.on("data", function(data){ 
      const weatherData = JSON.parse(data); 
      const temp = weatherData.main.temp; 
      const weatherDescription = weatherData.weather[0].description; 
      res.write("<p>The weather is currently " + weatherDescription + "</p>"); 
      res.write("<h1>The temperature in "+ query +" is " + temp +" degrees Celcius.</h1>"); 
      res.send(); 
    }) 
  }) 
}); 

这样你的天气应用就更稳定啦!

内容的提问来源于stack exchange,提问作者Ashraful Islam Joy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:31:45