调用OpenWeatherMap API返回401错误,排查指向temp变量,求解决方案
解决建议
1. 修复API请求URL的空格问题
你的URL拼接时,参数键与值之间多了冗余空格(比如q= 、appid= 、units= ),这会导致OpenWeatherMap无法正确识别API密钥和查询参数,直接返回401未授权错误。
修改URL拼接代码,去掉参数后的空格:
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apikey + "&units=" + unit;
2. 增加错误状态码处理
当API返回401等非200状态码时,不要直接解析响应数据,否则会因weatherData.main不存在导致temp变量报错。在响应回调中先判断状态码:
https.get(url, function(response){ console.log(response.statusCode); if (response.statusCode !== 200) { res.send("<h1>获取天气数据失败:状态码 " + response.statusCode + "</h1>"); return; } // 后续正常数据处理逻辑 });
3. 验证API密钥有效性
确认你的API密钥be542b6232b2bc2d159d89e25bf419fc是否在OpenWeatherMap平台已激活,无过期或权限限制。可直接在浏览器中访问修改后的URL,测试能否返回正常JSON数据。
4. 处理响应数据的完整性
response.on("data")可能分多次接收数据,直接解析易得到不完整JSON,引发解析错误。建议拼接完整数据后再解析:
https.get(url, function(response){ let rawData = ''; response.on('data', (chunk) => { rawData += chunk; }); response.on('end', () => { try { const weatherData = JSON.parse(rawData); const temp = weatherData.main.temp; const weatherDescription = weatherData.weather[0].description; const icon = weatherData.weather[0].icon; const imageURL = "https://openweathermap.org/img/wn/" + icon + "@2x.png"; res.write("<p>The weather is currently " + weatherDescription + " </p>"); res.write("<h1>The temperature in " + query + " is " + temp + " degree celsius.</h1>"); res.write("<img src = " + imageURL + ">"); res.send(); } catch (e) { res.send("<h1>解析天气数据失败:" + e.message + "</h1>"); } }); });
内容的提问来源于stack exchange,提问作者Amna Iftikhar
相关产品推荐
相关产品推荐

