React JS中调用位置API获取天气信息遇BUG求助
天气应用API请求错误修复方案
问题根源
- 异步函数调用错误:
getCity()是异步函数,直接拼接进URL时,实际传入的是Promise对象而非城市字符串,导致API请求URL格式错误,无法正确识别城市参数。 - 城市名处理逻辑错误:原代码中
replace(/s/g, "")会移除所有字母s,而非城市名中的空格,这会导致像"San Francisco"这类带空格的城市名被错误处理,无法匹配API要求的格式。
修正后的代码
async function getCity() { let response = await fetch("https://ipinfo.io/json?token=MYTOKEN"); let data = await response.json(); let city = data.city; // 移除城市名中的所有空格并转为小写 return city.replace(/\s+/g, "").toLowerCase(); } async function getWeatherInfo() { // 等待异步函数返回城市名称字符串 let cityName = await getCity(); // 用模板字符串拼接URL,避免Promise对象混入 let apiUrl = `https://api.openweathermap.org/data/2.5/weather?units=imperial&q=${cityName}&appid=MYAPIKEY`; let weatherResponse = await fetch(apiUrl); // 处理API请求失败的情况 if (!weatherResponse.ok) { throw new Error(`请求失败,状态码:${weatherResponse.status}`); } let weatherData = await weatherResponse.json(); console.log(weatherData.main.temp); } // 捕获执行过程中的错误并输出 getWeatherInfo().catch(err => console.error(err));
关键修正说明
- 调用
getCity()时添加await,确保获取到实际的城市字符串后再拼接URL。 - 替换正则表达式为
/\s+/g,专门匹配并移除城市名中的空格,保留正确的城市标识。 - 增加API请求状态校验,避免因API返回错误导致后续代码崩溃。
- 使用模板字符串拼接URL,提升代码可读性和维护性。
内容的提问来源于stack exchange,提问作者JaxSyntax
相关产品推荐
相关产品推荐

