Node.js调用OpenWeather API:地理编码获取lat/lon失败问题
解决OpenWeather API调用中的TypeError: Cannot read properties of undefined (reading 'lat')问题
问题根源
你犯了一个核心错误:只是把地理编码API的URL存成了字符串,并没有实际发送HTTP请求去获取数据。geoCodingApi只是个普通字符串,不存在body属性,所以读取geoCodingApi.body.lat时必然抛出Cannot read properties of undefined错误。
修复步骤
- 安装HTTP请求库(推荐用
axios,比Node.js内置的http模块更易用):
npm install axios
- 在代码中引入
axios,并在POST路由里先请求地理编码API,拿到响应后再提取经纬度 - 注意:OpenWeather的地理编码API返回的是数组格式的结果,需要取数组的第一个元素来获取
lat和lon
完整修复后的Node.js代码
const express = require("express"); const bodyParser = require("body-parser"); const axios = require("axios"); // 新增引入axios const app = express(); app.use(bodyParser.urlencoded({ extended: true })); const apiKey = "-hidden-"; // 建议用环境变量存储,不要硬编码 app.get("/", function(req, res) { res.sendFile(__dirname + "/index.html"); }); app.post("/", async function(req, res) { // 改成async函数,方便用await处理异步请求 try { const cityName = req.body.cName; // 1. 发送地理编码API请求 const geoResponse = await axios.get(`http://api.openweathermap.org/geo/1.0/direct?q=${cityName}&appid=${apiKey}`); // 检查是否获取到有效结果 if (geoResponse.data.length === 0) { return res.send("未找到该城市,请检查输入"); } // 2. 从响应中提取经纬度 const { lat, lon } = geoResponse.data[0]; // 3. 构造天气API请求并返回数据(也可以只返回链接) const weatherResponse = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`); res.send(`当前天气数据:<pre>${JSON.stringify(weatherResponse.data, null, 2)}</pre>`); // 如果只想返回天气API链接,替换成下面代码: // const openWeatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`; // res.send(openWeatherUrl); } catch (error) { // 捕获请求错误,方便调试 res.send(`请求出错:${error.message}`); } }); app.listen(3000, function() { console.log("Server is running on port 3000"); });
关键说明
- 用
async/await处理异步HTTP请求,避免回调地狱,代码更清晰 - 增加了错误捕获逻辑,能处理城市不存在、API请求失败等情况
- 地理编码API返回的是数组,必须取
data[0]才能拿到具体城市的经纬度 - 建议把API Key存到环境变量(比如用
dotenv包),不要直接写在代码里,避免泄露
内容的提问来源于stack exchange,提问作者shahriarshafei
相关产品推荐
相关产品推荐

