Node.js城市信息查询模块调试求助:API调用代码异常排查
南非城市信息查询模块代码问题排查与修复
一、直接导致运行失败的语法错误
- 模板字符串语法错误:所有使用
${变量}的字符串都未用反引号`包裹,同时部分字符串中$与{}之间存在多余空格,触发JavaScript语法解析错误。- 错误示例:
await fetch(${GEO_API_URL}?cityId=${cityId}, ...)、console.error(Error fetching city details: $ {error.message}) - 修正方式:将这些字符串用反引号包裹,同时去掉
$与{}之间的空格,例如:await fetch(`${GEO_API_URL}?cityId=${cityId}`, ...)console.error(`Error fetching city details: ${error.message}`)
- 错误示例:
二、API请求与数据处理的逻辑问题
- 未校验HTTP响应状态:仅解析JSON不足以判断请求是否成功,需先检查
response.ok(状态码200-299),否则抛出错误,避免将错误响应的JSON当作有效数据处理。 - CityId参数不匹配:GeoDB Cities API的
cityId是平台自身的数值ID,而非维基数据ID(如示例中的Q5465),会导致查询无结果。建议改用按城市名+国家筛选的接口(如/cities?namePrefix=Johannesburg&countryIds=ZA),或先通过GeoDB的搜索接口获取正确的城市ID。 - 异常处理不完整:
getCityAndWeatherInfo的catch块仅打印错误但未向上抛出,导致顶层调用无法感知错误;同时顶层调用缺少.catch()处理未捕获的异常。
三、修复后的完整代码
import fetch from 'node-fetch' // Constants for API details const GEO_API_URL = 'https://wft-geo-db.p.rapidapi.com/v1/geo/cities'; const WEATHER_API_URL = 'https://weatherbit-v1-mashape.p.rapidapi.com/current'; // Separate headers for the two APIs const GEO_HEADERS = { 'X-RapidAPI-Host': 'wft-geo-db.p.rapidapi.com', 'X-RapidAPI-Key': '5470f285aemshd79624e8065945cp1df6d3jsn4b3dac9e4d7c' }; const WEATHER_HEADERS = { 'X-RapidAPI-Host': 'weatherbit-v1-mashape.p.rapidapi.com', 'X-RapidAPI-Key': '5470f285aemshd79624e8065945cp1df6d3jsn4b3dac9e4d7c' }; const getCityDetails = async(cityId) => { try { const response = await fetch(`${GEO_API_URL}?cityId=${cityId}`, { method: 'GET', headers: GEO_HEADERS }); // 检查HTTP响应状态 if (!response.ok) { throw new Error(`GeoDB API request failed: ${response.statusText}`); } const data = await response.json(); if (data.data && data.data.length > 0) { return data.data[0]; } else { throw new Error('City not found'); } } catch (error) { console.error(`Error fetching city details: ${error.message}`); throw error; } }; const getWeatherDetails = async(latitude, longitude) => { try { const response = await fetch(`${WEATHER_API_URL}?lat=${latitude}&lon=${longitude}`, { method: 'GET', headers: WEATHER_HEADERS }); // 检查HTTP响应状态 if (!response.ok) { throw new Error(`Weatherbit API request failed: ${response.statusText}`); } const data = await response.json(); if (data.data && data.data.length > 0) { return data.data[0]; } else { throw new Error('Weather data not available'); } } catch (error) { console.error(`Error fetching weather details: ${error.message}`); throw error; } }; const getCityAndWeatherInfo = async(cityId) => { try { const cityDetails = await getCityDetails(cityId); const weatherDetails = await getWeatherDetails(cityDetails.latitude, cityDetails.longitude); return { population: cityDetails.population, elevation: cityDetails.elevationMeters, currentTemperature: weatherDetails.temp }; } catch (error) { console.error(`Error fetching combined data: ${error.message}`); // 重新抛出错误,让顶层调用感知 throw error; } }; // 示例:改用GeoDB的有效城市ID(比如约翰内斯堡的ID为15220) getCityAndWeatherInfo('15220') .then(data => { console.log(data); }) // 处理顶层未捕获的异常 .catch(err => { console.error(`Final error: ${err.message}`); });
内容的提问来源于stack exchange,提问作者Marvie
相关产品推荐
相关产品推荐

