我正在使用openweathermap.org我的 React 应用程序中的 api。它工作正常,但当用户输入错误的城市名称时不会显示错误。 有时也显示
cannot read property 'message' of undefined
我的 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);
});
}
}
react 文件:
openWeatherMap.getTemp(location)
.then(function(temp){
that.setState({
location:location,
temp:temp,
isLoading:false
})
},function(err){
alert(err);
});
最佳答案
这是一个没有任何未处理错误的代码版本 - 基于 axios documentation和openweathermap API documentation
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(res => {
if (res.data.cod === 200){
return JSON.stringify(res.data);//.data.main.temp;
}
throw res.data.cod;
}, res => {
throw (res && ((res.response && res.response.data && (res.response.data.message || res.response.data)) || (res.code))) || res;
});
}
}
react 文件:
openWeatherMap.getTemp(location).then(function(temp){
that.setState({
location:location,
temp:temp,
isLoading:false
})
},function(err){
alert(err);
});
那个抛出看起来很丑陋,但我不知道你可能会遇到什么类型的错误......这种丑陋是基于我可以通过各种方式“强制”的错误
关于javascript - 显示 openweathermap API 错误时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977279/