Express服务器提交输入后出现temp未定义错误,如何排查解决?
问题解决:Express服务器提交后触发“temp is undefined”错误
核心错误原因及修复
- API接口结构误用
OpenWeatherMap的/data/2.5/weather接口返回的JSON结构中没有list字段,list是逐小时预报接口/forecast的返回字段。你错误地用了weatherData.list[0].main.temp,正确的温度字段路径是weatherData.main.temp。
把这行代码:
const temp1 = weatherData.list[0].main.temp;
替换为:
const temp1 = weatherData.main.temp;
- 数据分块接收问题
https.get的data事件会分多次返回数据,直接在单次data事件里解析JSON可能导致解析失败(比如数据不完整),应该先收集所有数据,再在end事件里解析:
https.get(url, function(response){ console.log(response.statusCode); let rawData = ''; response.on("data", function(chunk){ rawData += chunk; }); response.on("end", function(){ try { const weatherData = JSON.parse(rawData); const temp1 = weatherData.main.temp; const description = weatherData.weather[0].description; res.write("<h1>its " + description +" and "+temp1+"</h1>"); res.send(); } catch (err) { console.error('解析JSON出错:', err); res.status(500).send('获取天气数据失败'); } }); });
- 额外错误处理建议
- 增加HTTP状态码判断:如果
response.statusCode不是200(比如404城市不存在、401API密钥错误),直接返回错误提示 - 处理API返回的错误信息,比如当城市不存在时,OpenWeatherMap会返回
cod: 404,可以捕获并提示用户
修复后的完整代码示例
const express = require('express'); const https = require('https'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/",function(req,res){ res.sendFile(__dirname + "/index.html"); }); app.post("/",function(req,res){ const query = req.body.cityName; const apiKey = "你的API密钥"; // 替换为实际有效密钥 const units = "metric"; const url = `https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=${apiKey}&units=${units}`; https.get(url, function(response){ console.log(response.statusCode); let rawData = ''; response.on("data", function(chunk){ rawData += chunk; }); response.on("end", function(){ if (response.statusCode !== 200) { const errorData = JSON.parse(rawData); return res.status(response.statusCode).send(`错误:${errorData.message}`); } try { const weatherData = JSON.parse(rawData); const temp1 = weatherData.main.temp; const description = weatherData.weather[0].description; res.write(`<h1>当前天气:${description},气温:${temp1}℃</h1>`); res.send(); } catch (err) { console.error('数据解析失败:', err); res.status(500).send('服务器内部错误'); } }); }).on('error', (err) => { console.error('请求API失败:', err); res.status(500).send('无法连接天气服务器'); }); }); app.listen(3000, () => { console.log('Listening on port 3000'); });
内容的提问来源于stack exchange,提问作者IROM
相关产品推荐
相关产品推荐

