在处理用本机编写的天气应用程序时,我发现“网络请求失败”#39; Android上的应用程序正常运行时Android上的错误。
这是获取功能 -
componentDidMount: function() {
navigator.geolocation.getCurrentPosition(
location => {
// this variable will contain the full url with the new lat and lon
var formattedURL = REQUEST_URL + "lat=" + location.coords.latitude + "&lon=" + location.coords.longitude+"&APPID=e5335c30e733fc682907a126dab045fa";
// this will output the final URL to the Xcode output window
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(formattedURL);
// get the data from the API
this.fetchData(formattedURL);
},
error => {
console.log(error);
});
},
// fetchdata takes the formattedURL, gets the json data and
// sets the apps backgroundColor based on the temperature of
// the location
fetchData: function(url) {
fetch(url)
.then((response) => response.json())
.then((responseData) => {
// set the background colour of the app based on temperature
var bg;
var temp = parseInt(responseData.main.temp);
if(temp < 14) {
bg = BG_COLD;
} else if(temp >= 14 && temp < 25) {
bg = BG_WARM;
} else if(temp >= 25) {
bg = BG_HOT;
}
// update the state with weatherData and a set backgroundColor
this.setState({
weatherData: responseData,
backgroundColor: bg
});
})
.done();
},
我还在stackoverflow上提到了其他问题,但它们都围绕将localhost更改为本地ip地址,如127.0.0.1。在我的情况下,我没有使用localhost。
答案 0 :(得分:2)
检查您的模拟器旁边的 Android模拟器选项面板,您将拥有更多选项,然后转到手机并检查数据状态和网络类型。尝试将网络类型更改为'完整',将数据状态更改为'主页'。尝试网络类型和数据状态的各种选项,并检查其是否正常工作......
答案 1 :(得分:0)
android:usesCleartextTraffic="true"
中添加AndroidManifest.xml
行。