【发布时间】:2017-02-01 10:25:12
【问题描述】:
我在我的反应应用程序中使用openweathermap.org api。它工作正常,但当用户输入错误的城市名称时不会显示错误。 有时也会显示
无法读取未定义的属性“消息”
我的 openweather.js
import axios from 'axios';
const weather_url = 'http://api.openweathermap.org/data/2.5/weather?appid=************&units=metric';
export default {
getTemp(location){
var encodedLocation = encodeURIComponent(location);
var requrl = `${weather_url}&q=${encodedLocation}`;
return axios.get(requrl).then(function(res){
if(res.data.cod && res.data.message){
throw new Error(res.message);
} else{
return res.data.main.temp;
}
},function(res){
return new Error(res.data.message);
});
}
}
反应文件:
openWeatherMap.getTemp(location)
.then(function(temp){
that.setState({
location:location,
temp:temp,
isLoading:false
})
},function(err){
alert(err);
});
【问题讨论】:
-
@JaromandaX 不起作用:(
-
@JaromandaX 同样的错误
-
@JaromandaX 使用 chrome 最新版本。也更改为
return new Error(res.message);在控制台中出现 2 个错误:502 (Bad Gateway)和``未捕获(承诺)错误:对象作为 React 子项无效(发现:错误:请求失败,状态码为 502)。如果您打算渲染一组子对象,请改用数组或使用 React 附加组件中的 createFragment(object) 包装对象。检查WeatherMessage的渲染方法。 -
@JaromandaX 相同的初始错误 :(
-
您需要阅读有关错误的documentation for axios 以及有关响应格式的documentation for openweathermap。虽然它确实没有提及消息,但消息至少存在于错误中 - 顺便说一下,错误处理程序中将是
res.response.data.message
标签: javascript reactjs error-handling react-router openweathermap