问题
I'm using React native for developing an android application. With this fetch request I'm getting the error TypeError: network request failed
:
fetch('https://pixabay.com/api/?key=MY_KEY&q='+ this.props.jsondata.city.name +'&lang=en&image_type=photo&orientation=horizontal&category=travel&safesearch=true')
.then(response => {
console.dir(response);
if (!response.ok) {
throw Error(data.statusText);
}
return response.json();
})
.then(json => {
console.log(json.hits[0].largeImageURL)
this.setState(() => {
return {backImage: json.hits[0].largeImageURL};
});
})
.catch(err => {
console.log('Unable to search image! ' + err);
});
I've already searched online but this problem appears only with localhost addresses or http, that is not my case. The request is inside the componentDidMount()
function. I've made a similar request (with the same structure) in an another place of the application but there is no error there. I'm using a real android device to testing the app with the react-native app compiled in android native code.
回答1:
Add
android:usesCleartextTraffic="true"
inAndroidManifest.xml
.Delete all debug folder from your android folder.
回答2:
You could try verifying if the device has internet connection before making the http request. React Native has a module to verify that: Netinfo.
import { NetInfo } from 'react-native';
... your component code
checkInternetConnection = () => {
return NetInfo.isConnected.fetch().then((isConnected) => {
return isConnected;
});
};
回答3:
I suppose the main reason for the error is emulator SSL certificate issue. To solve the issue you may use a real device for testing your app or you may set up a persistent Certificate Authority (CA)
回答4:
None of these solutions worked since everywhere folks were referring to "localhost", which i was not using i found a solution that worked for me, for which you need to add the required host in the following file
android/app/src/debug/res/xml/react_native_config.xml
.
This is my how my xml looks now:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">localhost</domain>
<domain includeSubdomains="false">10.0.2.2</domain>
<domain includeSubdomains="false">10.0.3.2</domain>
<domain includeSubdomains="true">facebook.github.io</domain>
</domain-config>
</network-security-config>
After which my below fetch request started working:
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
Alert.alert(JSON.stringify(responseJson));
});
.catch((error) => {
console.error(error);
});
来源:https://stackoverflow.com/questions/52163801/react-native-typeerror-network-request-failed-with-fetch