Today, when I was writing a demo of Network Request with React Native, the emulators kept telling me Network Request Failed
, which was very annoying, baidu search for a long time did not find the answer I wanted, someone said on stackoverflow that this error only appeared in the development mode, but the production version would not appear, but it didn’t solve the problem at all. Another says: If you’re using FETCH to get data, and you’re using POST, notice that Headers has to add a request header. You can’t use the body when the request is for GET, you must include the body when it is for POST, and once you set the header, everything works fine. However, the fetch method used by me does not need to add any headers, so the problem of Network Request Failed has not been solved.
To prevent code errors, I directly copied the official sample code, as follows
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.movies);
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
I put this code directly into the browser console console to run, and found that everything was ok, the console successfully output content. Then it could be the ios emulator.
Now that fecth API is problematic try using XMLHttpRequest instead, and the console output the Resource could not be loaded because the app Transport Security policy requires the use of a secure Connection, Baidu search only found that iOS9 introduced the new feature App Transport Security (ATS). The new feature requires that networks accessed within the App must use the HTTPS protocol, meaning that the Api interface must be HTTPS in the future. But my project USES HTTP, and I can’t immediately switch to HTTPS for transport.
Fortunately there is an alternative solution
1. Add NSAppTransportSecurity type Dictionary to info.plist.
2. Add nsallowsarbitraryoccurrence type Boolean under NSAppTransportSecurity, value set to YES
For details, please refer to this document for the resolution that iOS9 HTTP does not work properly