Network request failed - fetching from localhost ReactNative - android

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

These solutions did not work.
What did work:
Download ngrok (https://ngrok.com/), signup, and connect your account. ngrok creates a private https localhost tunnel.
Setup - https://dashboard.ngrok.com/get-started/setup
Unzip to install ngrok:
unzip /path/to/ngrok.zip
Connect your ngrok account (Non functioning example auth token):
ngrok config add-authtoken 2ySPR5UeS3Fjf5YAblNRe7ZcV1o_9sdf2SDFGHjEQaOCE6xEi
Use the command (with your port number):
ngrok http 8080
Once ngrok is online, replace your localhost API address:
http://localhost:8080
http://127.0.0.1:8080
http://192.168.0.100:8080
With the forwarding web address (Non functioning example address):
https://ebda-61-137-45-130.ngrok.io
I've used ngrok for testing APIs on a variety of networks without issue. So far its the only foolproof method I've found for testing APIs using localhost.

Related

Android: [AxiosError: Network Error] Expo React Native

Relevant modules used:
"expo": "~46.0.9"
"axios": "^0.27.2"
I'm trying to fetch some data, everything works just fine on iOS devices but the problem comes when using an Android, the network fails for some reason:
Android Running app on sdk_gphone64_arm64
[AxiosError: Network Error]
Here's the line of code that causes it:
const { data } = await axios.get('http:<my IP or 'localhost'>:<port>/endpoint');
Any ideas on how to fix it?
The solution for this was that Axios didn't really need my real IP address. It needed the IP that expo gives you when you start the metro bundler.
So instead of:
axios.get('http:<my IP or 'localhost'>:<port>/endpoint')
I changed it for:
axios.get('http:192.168.100.20:<port>/endpoint')
Now it is working.

Unable to open asset URL - ionic, Android

I'm building an ionic application and I faced with an issue that affect only the Android devices.
I have some public images that I'd like to load like this:
<img src={imageurl} alt="" />
I'm using this plugin https://github.com/capacitor-community/http to make API calls, to avoid CORS issues. All the API calls are working on both platforms, but the images only works on iOS.
If I check the inspector this is the error message I get:
If I check the Android Studio logs I see these error messages: E/Capacitor: Unable to open asset URL:
If I'm using axios to make the API calls it works fine on Android but then it'll break on iOS due to CORS issues.
I was trying to separate the API calls and only use the native plugin on iOS but I don't think that is possible.. Android was able to make the calls with axios but response was always got response like this:
Android AndroidManifest is extended with this: android:usesCleartextTraffic="true"
webDir: "build",
bundledWebRuntime: false,
android: {
allowMixedContent: true
},
server: {
cleartext: true,
hostname: "baseurl.hu",
iosScheme: "localhost",
androidScheme: "https"
},
This is how I run the app:
ionic capacitor copy android
Android Studio run.

Ionic Android app can't connect to local IP address

I am running my android app with ionic cordova run android, and doing a HTTP get to a local ip address:
this.http.get('http://192.168.2.124:8080')
.pipe(map((response: any) => {
alert(response);
return response;
}),
catchError(map((error: Response | any) => {
alert(error);
console.error('API error: ', error);
return error;
})));
However, nothing happens at all, no errors either.
Note:
replacing the host with something I deployed on the cloud works just fine;
using the phone's web browser to navigate to that endpoint also works.
I'm lost: is there a android or ionic configuration I'm missing to allow this?
Thank you

Network Error on API requests on Expo Android

I am developing a React Native app using Expo and I recently ran into a weird issue. API requests don't work on Android devices however they're totally fine on iOS. The server I'm trying to connect to isn't localhost. I tried to use axios and fetch, both result in Network Error and the server doesn't receive a request. I also made requests to open APIs which got me the same error, so I believe the problem isn't on the server's side.
Here's the code of the request:
const axiosInstance = axios.create({
timeout: 120000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
const res = await axiosInstance.post(`${serverHostApi}/merchant/login`, payload)
Here's the stack trace:
Network Error
- node_modules\axios\lib\helpers\normalizeHeaderName.js:8:14 in processHeader
* http://192.168.150.71:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&minify=false&hot=false:226876:26 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575:10 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389:6 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425:19 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
I'm using Expo 38.0.0, React Native SDK 38.0.2.
Any help would be highly appreciated!
If this is happening only in the android app. It might be a case you accidently removed internet permission from your android app. Kindly check you have proper permission in the Android Manifest File.
To Check , go the YourApp/android/app/src/main and open AndroidManifest.xml
and check if you have this line
<uses-permission android:name="android.permission.INTERNET" />
if you don't have it , add this line inside your Manifest file like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
I also ran into this problem.
You can use tools like SSL Labs to test the validity of your SSL certificate.
SSL SERVER TEST
I solved it with this method
Only way that I found to resolve is downgrade the version. Or you should make sure that TLS 1.0 and TLS 1.1 is disabled on the server.
"axios": "0.24.0"

React Native Fetch on Android returns Network request failed

I am building a React Native mobile application that is using a Laravel backend, currently running on localhost:8000. When making a fetch request from an Android device to my server, my application gets the following error logs:
My code is below:
export default class App extends Component {
login() {
fetch('http://localhost:8000/api/establishments/get')
.then((response) => response.json())
.then((responseJson) => {
console.log('success!');
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<TouchableOpacity activeOpacity={.5} onPress={() => this.login()}>
<Text>Sign In</Text>
</TouchableOpacity>
);
}
}
When I copy and paste the exact route into my browser, the server responds successfully and completely as expected. I believe it is an issue with network permissions from my application? I have only just began learning React Native a week ago and would appreciate any help at all.
iOS runs in a simulator while Android runs in an emulator.
Emulator emulates a real device, while simulator only imitates a device.
Therefore localhost on Android points to the emulated Android device instead of the machine where your server runs.
You should change localhost in yours request paths with the IP address of your machine.
More details at: https://github.com/facebook/react-native/issues/10404#issuecomment-267303151
I suspect that 127.0.0.1 or localhost will point to the emulator itself in your computer where the server is currently running. Try replacing 127.0.0.1 / localhost with 10.0.2.2 if you are on AVD or 10.0.3.2 if you are on Genymotion or with your computer's actual IP address. In addition, you should also make sure that your android app can use internet. You can do that by adding
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml.
Founded solution for Laravel and react native (Physical device)
open cmd run ipconfig copy ipv4 address for example my ipv4 address is 192.168.43.235
Connect same network for laptop and physical device or open hotspot and connect same network
Now run command start laravel backend php artisan serve --host=192.168.43.235 --port=8000
change api url from react native api service
apiServise.js
import axios from 'axios';
const api_url = 'http://192.168.43.235:8000';
export const getCategories = request =>
axios
.get(api_url + '/api/categories', {
params: request || {},
})
.then(response => response.data);
homescreen.js
import {getCategories} from '../services/ApiService';
async fetchCategories() {
await getCategories()
.then(response => {
this.setState({
dataCategories: response
});
})
.catch(error => {
console.log(error);
});
}
Now run command start react native app react-native run-android
that is all...now api request working fine.
Change http://localhost:8000/api/establishments/get localhost with, which can your emulator reach generally 10.0.2.2 ;) have phun.

Categories

Resources