Express JS中.env配置后调用OpenWeatherMap API报错求助
问题分析与解决方案
核心问题
报错TypeError: Cannot read property 'temp' of undefined说明weatherData.main不存在,本质是API请求返回的不是预期的天气数据,根源在于dotenv配置错误导致环境变量未正确加载,进而拼接出无效的API请求URL。
具体修复步骤
1. 修正dotenv配置位置与方式
把dotenv的初始化移到文件最顶部,不要放在POST请求处理函数内,且避免重复调用:
const express = require("express"); const https = require("https"); const { restart } = require("nodemon"); const bodyParser = require("body-parser"); const dotenv = require('dotenv'); // 初始化dotenv,放在最顶部 dotenv.config({ path: __dirname + '/.env' }); // 确保路径指向项目根目录的.env文件 const app = express(); // 后续代码不变...
2. 检查.env文件内容
确保你的.env文件在项目根目录,内容格式正确:
API_URL=https://api.openweathermap.org/data/2.5/weather?q= API_KEY=你的OpenWeatherMap密钥
注意API_URL末尾必须包含q=,这是OpenWeatherMap API要求的查询参数格式。
3. 优化API URL拼接(可选但推荐)
用ES6模板字符串替代字符串拼接,避免语法错误:
const url = `${weatherUrl}${city}&appid=${apiKey}&units=${unit}`;
4. 添加错误处理逻辑
在API响应中先判断请求是否成功,避免因返回错误数据导致崩溃:
https.get(url, function(response){ console.log("API响应状态码:", response.statusCode); // 调试用,可删除 let rawData = ''; // 正确处理流式数据(原代码只处理了data事件,可能数据不完整) response.on("data", function(chunk){ rawData += chunk; }); response.on("end", function(){ try { const weatherData = JSON.parse(rawData); // 检查是否返回错误 if (weatherData.cod !== 200) { res.send(`<h1>错误:${weatherData.message}</h1>`); return; } // 正常处理数据 const temp = weatherData.main.temp; const weatherDescription = weatherData.weather[0].description; const weatherIcon = weatherData.weather[0].icon; const imageUrl = `http://openweathermap.org/img/wn/${weatherIcon}@2x.png`; res.write(`<p>The Weather is currently ${weatherDescription}</p>`); res.write(`<h1>The temprerature in ${city} now is ${temp} degress Celcius.</h1>`); res.write(`<img src="${imageUrl}">`); res.send(); } catch (err) { console.error("解析API数据出错:", err); res.send("<h1>获取天气数据失败</h1>"); } }); })
原代码的
data事件只处理了单次数据块,可能导致JSON解析不完整,改用end事件处理完整数据更可靠。
额外注意事项
- 确保
.env文件已添加到.gitignore,避免密钥泄露。 - 测试前重启nodemon,确保环境变量生效。
内容的提问来源于stack exchange,提问作者Darkhole
相关产品推荐
相关产品推荐

