I am getting a Network request failed when trying to fetch from localhost in ReactNative for both android and ios devices.
I've tried following previous solutions but nothing seemed to work for me. I followed this tutorial: https://revs.runtime-revolution.com/connecting-react-native-to-localhost-65e7ddf43d02
For iOS: I edited the info.plist and added the following code and reinstalled the app on my simulator but it still didn't work.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
For Android: I used my IP instead of 'localhost' for my fetching URL but it still didn't work. I also made configurations to AndroidManifest.xml following the steps in the tutorial but it still doesn't work.
Any other solutions???
PS. I am using a Macbook. My REST API is using SQL database and asp.net core. I am trying to fetch a json.
Error: Network Request Failed
Fetch code:
async getProjects1() {
const response = await fetch('https://127.0.0.1:5001/api/projects');
const data = await response.json();
this.setState({ projects: data, loading: false }, function(){console.log(this.state.projects)});
};
Your error message says that there is unhandled promise rejection, so i'd advise adding error handling as:
async getProjects1() {
try {
const response = await fetch('https://127.0.0.1:5001/api/projects');
const data = await response.json();
this.setState({ projects: data, loading: false }, function(){console.log(this.state.projects)});
} catch (err) {
console.log(err)
}
}
and this issue may be resolved, or you at least might get clearer error message.
I solved the issue. The error was not because of react native but from my asp.net core API. Basically, I just needed to change my code in the launchsettings.js in the Properties folder from "applicationUrl": "https://localhost:5001;http://localhost:5000"
to "applicationUrl": "http://localhost:5000"
This solved the issue and fetching from localhost in react native worked without any further issues. This stack question helped me figure this out: How to fix network error in react-native when access localhost api
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.